major cleanup:
[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 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46
47 import mir.log.LoggerWrapper;
48 import mir.servlet.ServletModule;
49 import mir.servlet.ServletModuleExc;
50 import mir.servlet.ServletModuleFailure;
51 import mir.util.FileFunctions;
52 import mir.util.HTTPRequestParser;
53 import mir.util.StringRoutines;
54 import mir.util.URLBuilder;
55
56 /*
57  *  ServletModuleFileEdit -
58  *  Allows one to do a basic edit of a file in a directory specified
59  *  in the config file.
60  *
61  * @author $Author: zapata $
62  * @version $Revision: 1.13.2.2 $ $Date: 2003/09/03 17:49:40 $
63  *
64  */
65
66 public class ServletModuleFileEdit extends ServletModule
67 {
68   private static ServletModuleFileEdit instance = new ServletModuleFileEdit();
69   public static ServletModule getInstance() { return instance; }
70
71   private Map directories;
72   private List directoryNames;
73
74   private FilenameFilter dirFilter;
75
76   private class FileEditDirectory {
77     private String name;
78     private FileFunctions.RegExpFileFilter filter;
79     private File rootDirectory;
80     private boolean recursive;
81
82     public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) {
83       name = aName;
84       rootDirectory = new File(aRootDirectory);
85       filter = new FileFunctions.RegExpFileFilter(aFilter);
86       recursive = aRecursive;
87     }
88
89     public String getName() {
90       return name;
91     }
92
93     public FileFunctions.RegExpFileFilter getFilter() {
94       return filter;
95     }
96
97     public File getRootDirectory() {
98       return rootDirectory;
99     }
100
101     public boolean getRecursive() {
102       return recursive;
103     }
104   }
105
106   private ServletModuleFileEdit() {
107     super();
108
109     logger = new LoggerWrapper("ServletModule.FileEdit");
110
111     directories = new HashMap();
112     directoryNames = new Vector();
113
114     String settings[] = configuration.getStringArray("ServletModule.FileEdit.Configuration");
115
116     if (settings!=null) {
117       for (int i = 0; i < settings.length; i++) {
118         String setting = settings[i].trim();
119
120         if (setting.length() > 0) {
121           List parts = StringRoutines.splitString(setting, ":");
122           if (parts.size() != 4) {
123             logger.error("config error: " + settings[i] + ", 4 parts expected");
124           }
125           else {
126             String name = (String) parts.get(0);
127             String directory = (String) parts.get(1);
128             String filter = (String) parts.get(2);
129             String recursive = (String) parts.get(3);
130
131             directories.put(name, new FileEditDirectory(name, directory, filter,
132                 recursive.equals("1") || recursive.toLowerCase().equals("y")));
133             directoryNames.add(name);
134           }
135         }
136       }
137     }
138
139     dirFilter = new FileFunctions.DirectoryFilter();
140   }
141
142   public List getEntries() {
143     return directoryNames;
144   }
145
146   public FileEditDirectory getDirectory(HttpServletRequest aRequest) throws ServletModuleExc {
147     FileEditDirectory result = (FileEditDirectory) directories.get(aRequest.getParameter("entry"));
148     if (result == null)
149       throw new ServletModuleExc("Unknown entry: " + aRequest.getParameter("entry"));
150
151     return result;
152   }
153
154   public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
155   {
156     listSubDirectory(getDirectory(aRequest), "/", aRequest, aResponse);
157   }
158
159   public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
160   {
161     try {
162       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
163
164       String filename = requestParser.getParameter("filename");
165       String subDirectory = requestParser.getParameterWithDefault("subdirectory", "");
166
167       if (filename == null)
168         throw new ServletModuleExc("No filename  specified");
169
170       editFile(getDirectory(aRequest), filename, subDirectory, aRequest, aResponse);
171     }
172     catch (Throwable e) {
173       throw new ServletModuleFailure(e);
174     }
175   }
176
177   public void enter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
178   {
179     try {
180       HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
181
182       String directoryName = requestParser.getParameter("directory");
183       String subDirectoryName = requestParser.getParameter("subdirectory");
184
185       if (directoryName==null | subDirectoryName==null)
186         throw new ServletModuleExc("No directory/subDirectory specified");
187
188       listSubDirectory(getDirectory(aRequest), subDirectoryName+File.separator+directoryName, aRequest, aResponse);
189     }
190     catch (Throwable e) {
191       throw new ServletModuleFailure(e);
192     }
193   }
194
195   public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
196   {
197     HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
198     String filename = requestParser.getParameter("filename");
199     String subDirectory = requestParser.getParameter("subdirectory");
200     String text = requestParser.getParameter("text");
201     FileEditDirectory directory = getDirectory(aRequest);
202
203     try {
204       File f = new File(new File(directory.getRootDirectory(), subDirectory), filename);
205
206       if (validateDirectory(directory, f)) {
207         StringReader in = new StringReader(text);
208         FileWriter out = new FileWriter(f);
209
210         int c;
211         while ( (c = in.read()) != -1)
212           out.write(c);
213         in.close();
214         out.close();
215
216         editFile(directory, filename, subDirectory, aRequest, aResponse);
217       }
218     }
219     catch (Throwable e) {
220       throw new ServletModuleFailure(e);
221     }
222   }
223
224   public void listSubDirectory(FileEditDirectory aDirectory, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
225   {
226     try {
227       Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
228       File dir = new File(aDirectory.getRootDirectory(), aSubDirectory);
229
230       if (!validateDirectory(aDirectory, dir) || !dir.isDirectory()) {
231         dir = aDirectory.getRootDirectory();
232         aSubDirectory = "";
233       }
234
235       responseData.put("filelist", FileFunctions.getDirectoryContentsAsList(dir, aDirectory.getFilter()));
236
237       if (aDirectory.getRecursive()) {
238         List dirs = new Vector();
239         if (!dir.getCanonicalPath().equals(aDirectory.getRootDirectory().getCanonicalPath()))
240           responseData.put("updir", new File(aSubDirectory).getParent());
241
242         dirs.addAll(FileFunctions.getDirectoryContentsAsList(dir, dirFilter));
243
244         responseData.put("dirlist", dirs);
245       }
246       else {
247         responseData.put("dirlist", null);
248         responseData.put("updir", null);
249       }
250
251       responseData.put("subdirectory", aSubDirectory);
252       responseData.put("entry", aDirectory.getName());
253
254       ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
255     }
256     catch (Throwable e) {
257       throw new ServletModuleFailure(e);
258     }
259   }
260
261   public void editFile(FileEditDirectory aDirectory, String aFileName, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
262   {
263     try {
264       File f = new File(new File(aDirectory.getRootDirectory(), aSubDirectory), aFileName);
265
266       if (!validateDirectory(aDirectory, f) || f.isDirectory() || !validateFile(aDirectory, f)) {
267         listSubDirectory(aDirectory, "", aRequest, aResponse);
268       }
269       else {
270         Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
271         URLBuilder urlBuilder = new URLBuilder();
272
273         urlBuilder.setValue("module", "FileEdit");
274         urlBuilder.setValue("do", "enter");
275         urlBuilder.setValue("entry", aDirectory.getName());
276         urlBuilder.setValue("directory", "");
277         urlBuilder.setValue("subdirectory", aSubDirectory);
278
279         FileReader in = new FileReader(f);
280         StringWriter out = new StringWriter();
281
282         int c;
283         while ( (c = in.read()) != -1)
284           out.write(c);
285         in.close();
286         out.close();
287
288         responseData.put("entry", aDirectory.getName());
289         responseData.put("text", out.toString());
290         responseData.put("filename", aFileName);
291         responseData.put("subdirectory", aSubDirectory);
292         responseData.put("returnurl", urlBuilder.getQuery());
293
294         ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
295       }
296     }
297     catch (Throwable e) {
298       throw new ServletModuleFailure(e);
299     }
300   }
301
302   protected boolean validateDirectory(FileEditDirectory aDirectory, File aFile) {
303     try {
304       return (aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath()));
305     }
306     catch (Throwable t) {
307       return false;
308     }
309   }
310
311   protected boolean validateFile(FileEditDirectory aDirectory, File aFile) {
312     try {
313       return aDirectory.getFilter().accept(aFile.getParentFile(), aFile.getName());
314     }
315     catch (Throwable t) {
316       return false;
317     }
318   }
319 }