some cosmetic change, organzied imports, and made some accesses in a static way
[mir.git] / source / mircoders / servlet / ServletModuleFileEdit.java
1 /*
2  * Copyright (C) 2001, 2002 The Mir-coders group
3  *
4  * This file is part of Mir.
5  *
6  * Mir is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Mir is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Mir; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * In addition, as a special exception, The Mir-coders gives permission to link
21  * the code of this program with  any library licensed under the Apache Software License,
22  * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
23  * (or with modified versions of the above that use the same license as the above),
24  * and distribute linked combinations including the two.  You must obey the
25  * GNU General Public License in all respects for all of the code used other than
26  * the above mentioned libraries.  If you modify this file, you may extend this
27  * exception to your version of the file, but you are not obligated to do so.
28  * If you do not wish to do so, delete this exception statement from your version.
29  */
30
31 package mircoders.servlet;
32
33 import java.io.File;
34 import java.io.FileReader;
35 import java.io.FileWriter;
36 import java.io.FilenameFilter;
37 import java.io.StringReader;
38 import java.io.StringWriter;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.Locale;
42 import java.util.Map;
43 import java.util.Vector;
44
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47
48 import mir.log.LoggerWrapper;
49 import mir.servlet.ServletModule;
50 import mir.servlet.ServletModuleExc;
51 import mir.servlet.ServletModuleFailure;
52 import mir.util.FileFunctions;
53 import mir.util.HTTPRequestParser;
54 import mir.util.StringRoutines;
55 import mir.util.URLBuilder;
56
57 /*
58  *  ServletModuleFileEdit -
59  *  Allows one to do a basic edit of a file in a directory specified
60  *  in the config file.
61  *
62  * @author $Author: rk $
63  * @version $Revision: 1.13.2.4 $ $Date: 2003/10/23 14:55:25 $
64  *
65  */
66
67 public class ServletModuleFileEdit extends ServletModule
68 {
69   private static ServletModuleFileEdit instance = new ServletModuleFileEdit();
70   public static ServletModule getInstance() { return instance; }
71
72   private Map directories;
73   private List directoryNames;
74
75   private FilenameFilter dirFilter;
76
77   private class FileEditDirectory {
78     private String name;
79     private FileFunctions.RegExpFileFilter filter;
80     private File rootDirectory;
81     private boolean recursive;
82
83     public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) {
84       name = aName;
85       rootDirectory = new File(aRootDirectory);
86       filter = new FileFunctions.RegExpFileFilter(aFilter);
87       recursive = aRecursive;
88     }
89
90     public String getName() {
91       return name;
92     }
93
94     public FileFunctions.RegExpFileFilter getFilter() {
95       return filter;
96     }
97
98     public File getRootDirectory() {
99       return rootDirectory;
100     }
101
102     public boolean getRecursive() {
103       return recursive;
104     }
105   }
106
107   private ServletModuleFileEdit() {
108     super();
109
110     logger = new LoggerWrapper("ServletModule.FileEdit");
111
112     directories = new HashMap();
113     directoryNames = new Vector();
114
115     String settings[] = configuration.getStringArray("ServletModule.FileEdit.Configuration");
116
117     if (settings!=null) {
118       for (int i = 0; i < settings.length; i++) {
119         String setting = settings[i].trim();
120
121         if (setting.length() > 0) {
122           List parts = StringRoutines.splitString(setting, ":");
123           if (parts.size() != 4) {
124             logger.error("config error: " + settings[i] + ", 4 parts expected");
125           }
126           else {
127             String name = (String) parts.get(0);
128             String directory = (String) parts.get(1);
129             String filter = (String) parts.get(2);
130             String recursive = (String) parts.get(3);
131
132             directories.put(name, new FileEditDirectory(name, directory, filter,
133                 recursive.equals("1") || recursive.toLowerCase().equals("y")));
134             directoryNames.add(name);
135           }
136         }
137       }
138     }
139
140     dirFilter = new FileFunctions.DirectoryFilter();
141   }
142
143   public List getEntries() {
144     return directoryNames;
145   }
146
147   public FileEditDirectory getDirectory(HttpServletRequest aRequest) throws ServletModuleExc {
148     FileEditDirectory result = (FileEditDirectory) directories.get(aRequest.getParameter("entry"));
149     if (result == null)
150       throw new ServletModuleExc("Unknown entry: " + aRequest.getParameter("entry"));
151
152     return result;
153   }
154
155   public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
156   {
157     listSubDirectory(getDirectory(aRequest), "/", aRequest, aResponse);
158   }
159
160   public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
161   {
162     try {
163       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
164
165       String filename = requestParser.getParameter("filename");
166       String subDirectory = requestParser.getParameterWithDefault("subdirectory", "");
167
168       if (filename == null)
169         throw new ServletModuleExc("No filename  specified");
170
171       editFile(getDirectory(aRequest), filename, subDirectory, aRequest, aResponse);
172     }
173     catch (Throwable e) {
174       throw new ServletModuleFailure(e);
175     }
176   }
177
178   public void enter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
179   {
180     try {
181       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
182
183       String directoryName = requestParser.getParameter("directory");
184       String subDirectoryName = requestParser.getParameter("subdirectory");
185
186       if (directoryName==null | subDirectoryName==null)
187         throw new ServletModuleExc("No directory/subDirectory specified");
188
189       listSubDirectory(getDirectory(aRequest), subDirectoryName+File.separator+directoryName, aRequest, aResponse);
190     }
191     catch (Throwable e) {
192       throw new ServletModuleFailure(e);
193     }
194   }
195
196   public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
197   {
198     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
199     String filename = requestParser.getParameter("filename");
200     String subDirectory = requestParser.getParameter("subdirectory");
201     String text = requestParser.getParameter("text");
202     FileEditDirectory directory = getDirectory(aRequest);
203
204     try {
205       File f = new File(new File(directory.getRootDirectory(), subDirectory), filename);
206
207       if (validateDirectory(directory, f)) {
208         StringReader in = new StringReader(text);
209         FileWriter out = new FileWriter(f);
210
211         int c;
212         while ( (c = in.read()) != -1)
213           out.write(c);
214         in.close();
215         out.close();
216
217         logAdminUsage(aRequest, f.getAbsolutePath(), "object modified");
218
219
220         editFile(directory, filename, subDirectory, aRequest, aResponse);
221       }
222     }
223     catch (Throwable e) {
224       throw new ServletModuleFailure(e);
225     }
226   }
227
228   public void listSubDirectory(FileEditDirectory aDirectory, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
229   {
230     try {
231       Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
232       File dir = new File(aDirectory.getRootDirectory(), aSubDirectory);
233
234       if (!validateDirectory(aDirectory, dir) || !dir.isDirectory()) {
235         dir = aDirectory.getRootDirectory();
236         aSubDirectory = "";
237       }
238
239       responseData.put("filelist", FileFunctions.getDirectoryContentsAsList(dir, aDirectory.getFilter()));
240
241       if (aDirectory.getRecursive()) {
242         List dirs = new Vector();
243         if (!dir.getCanonicalPath().equals(aDirectory.getRootDirectory().getCanonicalPath()))
244           responseData.put("updir", new File(aSubDirectory).getParent());
245
246         dirs.addAll(FileFunctions.getDirectoryContentsAsList(dir, dirFilter));
247
248         responseData.put("dirlist", dirs);
249       }
250       else {
251         responseData.put("dirlist", null);
252         responseData.put("updir", null);
253       }
254
255       responseData.put("subdirectory", aSubDirectory);
256       responseData.put("entry", aDirectory.getName());
257
258       ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
259     }
260     catch (Throwable e) {
261       throw new ServletModuleFailure(e);
262     }
263   }
264
265   public void editFile(FileEditDirectory aDirectory, String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
266   {
267     try {
268       File f = new File(new File(aDirectory.getRootDirectory(), aSubDirectory), aFileName);
269
270       if (!validateDirectory(aDirectory, f) || f.isDirectory() || !validateFile(aDirectory, f)) {
271         listSubDirectory(aDirectory, "", aRequest, aResponse);
272       }
273       else {
274         Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
275         URLBuilder urlBuilder = new URLBuilder();
276
277         urlBuilder.setValue("module", "FileEdit");
278         urlBuilder.setValue("do", "enter");
279         urlBuilder.setValue("entry", aDirectory.getName());
280         urlBuilder.setValue("directory", "");
281         urlBuilder.setValue("subdirectory", aSubDirectory);
282
283         FileReader in = new FileReader(f);
284         StringWriter out = new StringWriter();
285
286         int c;
287         while ( (c = in.read()) != -1)
288           out.write(c);
289         in.close();
290         out.close();
291
292         responseData.put("entry", aDirectory.getName());
293         responseData.put("text", out.toString());
294         responseData.put("filename", aFileName);
295         responseData.put("subdirectory", aSubDirectory);
296         responseData.put("returnurl", urlBuilder.getQuery());
297
298         ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
299       }
300     }
301     catch (Throwable e) {
302       throw new ServletModuleFailure(e);
303     }
304   }
305
306   protected boolean validateDirectory(FileEditDirectory aDirectory, File aFile) {
307     try {
308       return (aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath()));
309     }
310     catch (Throwable t) {
311       return false;
312     }
313   }
314
315   protected boolean validateFile(FileEditDirectory aDirectory, File aFile) {
316     try {
317       return aDirectory.getFilter().accept(aFile.getParentFile(), aFile.getName());
318     }
319     catch (Throwable t) {
320       return false;
321     }
322   }
323 }