KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > gui > fckeditor > FCKEditorSimpleUploadServlet


1 /**
2  * FCKeditor - The text editor for internet
3  * Copyright (C) 2003-2005 Frederico Caldeira Knabben
4  *
5  * Licensed under the terms of the GNU Lesser General Public License:
6  * http://www.opensource.org/licenses/lgpl-license.php
7  *
8  * For further information visit:
9  * http://www.fckeditor.net/
10  *
11  * File Name: SimpleUploaderServlet.java
12  * Java File Uploader class.
13  *
14  * Version: 2.3
15  * Modified: 2005-08-11 16:29:00
16  *
17  * File Authors:
18  * Simone Chiaretta (simo@users.sourceforge.net)
19  */

20
21 /**
22  *
23  * Magnolia and its source-code is licensed under the LGPL.
24  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
25  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
26  * you are required to provide proper attribution to obinary.
27  * If you reproduce or distribute the document without making any substantive modifications to its content,
28  * please use the following attribution line:
29  *
30  * Copyright 1993-2006 obinary Ltd. (http://www.obinary.com) All rights reserved.
31  *
32  */

33 package info.magnolia.cms.gui.fckeditor;
34
35 import info.magnolia.cms.beans.runtime.Document;
36 import info.magnolia.cms.core.Path;
37 import info.magnolia.cms.servlets.ContextSensitiveServlet;
38 import info.magnolia.cms.util.RequestFormUtil;
39
40 import java.io.File JavaDoc;
41 import java.io.IOException JavaDoc;
42 import java.io.PrintWriter JavaDoc;
43 import java.util.ArrayList JavaDoc;
44 import java.util.Hashtable JavaDoc;
45
46 import javax.servlet.ServletException JavaDoc;
47 import javax.servlet.http.HttpServletRequest JavaDoc;
48 import javax.servlet.http.HttpServletResponse JavaDoc;
49
50 import org.apache.commons.io.FileUtils;
51 import org.safehaus.uuid.UUIDGenerator;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55
56 /**
57  * Servlet to upload files. This is based on the SimpleUploaderServlet of the FCKeditor connector package<br>
58  * This servlet accepts just file uploads, eventually with a parameter specifying file type
59  * @author Simone Chiaretta (simo@users.sourceforge.net)
60  * @author Philipp Bracher
61  */

62
63 public class FCKEditorSimpleUploadServlet extends ContextSensitiveServlet {
64
65     private static final long serialVersionUID = -8512828615271068088L;
66
67     private static Logger log = LoggerFactory.getLogger(FCKEditorSimpleUploadServlet.class);
68
69     private static Hashtable JavaDoc allowedExtensions;
70
71     private static Hashtable JavaDoc deniedExtensions;
72
73     /**
74      * Initialize the servlet.<br>
75      * Retrieve from the servlet configuration the "baseDir" which is the root of the file repository:<br>
76      * If not specified the value of "/UserFiles/" will be used.<br>
77      * Also it retrieve all allowed and denied extensions to be handled.
78      */

79     public void init() throws ServletException JavaDoc {
80         allowedExtensions = new Hashtable JavaDoc(3);
81         deniedExtensions = new Hashtable JavaDoc(3);
82
83         allowedExtensions.put("file", stringToArrayList(getInitParameter("AllowedExtensionsFile")));
84         deniedExtensions.put("file", stringToArrayList(getInitParameter("DeniedExtensionsFile")));
85
86         allowedExtensions.put("image", stringToArrayList(getInitParameter("AllowedExtensionsImage")));
87         deniedExtensions.put("image", stringToArrayList(getInitParameter("DeniedExtensionsImage")));
88
89         allowedExtensions.put("flash", stringToArrayList(getInitParameter("AllowedExtensionsFlash")));
90         deniedExtensions.put("flash", stringToArrayList(getInitParameter("DeniedExtensionsFlash")));
91     }
92
93     /**
94      * Manage the Upload requests.<br>
95      * The servlet accepts commands sent in the following format:<br>
96      * simpleUploader?Type=ResourceType<br>
97      * <br>
98      * It store the file (renaming it in case a file with the same name exists) and then return an HTML file with a
99      * javascript command in it.
100      */

101     public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
102         super.doPost(request, response);
103         response.setContentType("text/html; charset=UTF-8");
104         response.setHeader("Cache-Control", "no-cache");
105         PrintWriter JavaDoc out = response.getWriter();
106
107         String JavaDoc typeStr = request.getParameter("type");
108
109         String JavaDoc retVal = "0";
110         String JavaDoc newName = "";
111         String JavaDoc fileUrl = "";
112         String JavaDoc errorMessage = "";
113
114         RequestFormUtil form = new RequestFormUtil(request);
115
116         Document doc = form.getDocument("NewFile");
117
118         if (extIsAllowed(typeStr, doc.getExtension())) {
119
120             try {
121                 // now copy the files to the special fck tmp folder
122
String JavaDoc uuid = UUIDGenerator.getInstance().generateTimeBasedUUID().toString();
123                 FileUtils.copyFileToDirectory(doc.getFile(), new File JavaDoc(Path.getTempDirectoryPath()
124                     + "/fckeditor/"
125                     + uuid));
126                 doc.delete();
127
128                 // the document will now point to the copied file
129
doc = new Document(new File JavaDoc(Path.getTempDirectoryPath()
130                     + "/fckeditor/"
131                     + uuid
132                     + "/"
133                     + doc.getFile().getName()), doc.getType());
134
135                 // save it to the session
136
FCKEditorTmpFiles.addDocument(doc, uuid);
137
138                 // make the temporary url ready for the editor
139
fileUrl = request.getContextPath() + "/tmp/fckeditor/" + uuid + "/" + doc.getFile().getName();
140
141             }
142             catch (Exception JavaDoc ex) {
143                 log.error("can't upload the file", ex);
144                 retVal = "203";
145             }
146
147         }
148         else {
149             log.info("Tried to upload a not allowed file [" + doc.getFileNameWithExtension() + "]");
150             retVal = "202";
151             errorMessage = "";
152         }
153
154         out.println("<script type=\"text/javascript\">");
155         out.println("window.parent.OnUploadCompleted("
156             + retVal
157             + ",'"
158             + fileUrl
159             + "','"
160             + newName
161             + "','"
162             + errorMessage
163             + "');");
164         out.println("</script>");
165         out.flush();
166         out.close();
167     }
168
169     /**
170      * Helper function to convert the configuration string to an ArrayList.
171      */

172
173     private ArrayList JavaDoc stringToArrayList(String JavaDoc str) {
174         String JavaDoc[] strArr = str.split("\\|");
175
176         ArrayList JavaDoc tmp = new ArrayList JavaDoc();
177         if (str.length() > 0) {
178             for (int i = 0; i < strArr.length; ++i) {
179                 tmp.add(strArr[i].toLowerCase());
180             }
181         }
182         return tmp;
183     }
184
185     /**
186      * Helper function to verify if a file extension is allowed or not allowed.
187      */

188
189     private boolean extIsAllowed(String JavaDoc fileType, String JavaDoc ext) {
190
191         ext = ext.toLowerCase();
192
193         ArrayList JavaDoc allowList = (ArrayList JavaDoc) allowedExtensions.get(fileType);
194         ArrayList JavaDoc denyList = (ArrayList JavaDoc) deniedExtensions.get(fileType);
195
196         if (allowList.size() == 0) {
197             if (denyList.contains(ext)) {
198                 return false;
199             }
200             return true;
201
202         }
203
204         if (denyList.size() == 0) {
205             if (allowList.contains(ext)) {
206                 return true;
207             }
208             return false;
209
210         }
211
212         return false;
213     }
214 }
215
Popular Tags