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