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