001: /*
002: * FCKeditor - The text editor for internet
003: * Copyright (C) 2003-2005 Frederico Caldeira Knabben
004: *
005: * Licensed under the terms of the GNU Lesser General Public License:
006: * http://www.opensource.org/licenses/lgpl-license.php
007: *
008: * For further information visit:
009: * http://www.fckeditor.net/
010: *
011: * File Name: SimpleUploaderServlet.java
012: * Java File Uploader class.
013: *
014: * Version: 2.3
015: * Modified: 2005-08-11 16:29:00
016: *
017: * File Authors:
018: * Simone Chiaretta (simo@users.sourceforge.net)
019: */
020:
021: package org.zkforge.fckez.uploader;
022:
023: import java.io.*;
024: import javax.servlet.*;
025: import javax.servlet.http.*;
026: import java.util.*;
027:
028: import org.apache.commons.fileupload.FileItem;
029: import org.apache.commons.fileupload.disk.DiskFileItemFactory;
030: import org.apache.commons.fileupload.servlet.ServletFileUpload;
031:
032: import javax.xml.parsers.*;
033: import org.w3c.dom.*;
034: import javax.xml.transform.*;
035: import javax.xml.transform.dom.DOMSource;
036: import javax.xml.transform.stream.StreamResult;
037:
038: /**
039: * Servlet to upload files.<br>
040: *
041: * This servlet accepts just file uploads, eventually with a parameter
042: * specifying file type
043: *
044: * @author Simone Chiaretta (simo@users.sourceforge.net)
045: */
046:
047: public class SimpleUploaderServlet extends HttpServlet {
048:
049: private static String baseDir;
050:
051: private static boolean debug = false;
052:
053: private static boolean enabled = false;
054:
055: private static Hashtable allowedExtensions;
056:
057: private static Hashtable deniedExtensions;
058:
059: /**
060: * Initialize the servlet.<br>
061: * Retrieve from the servlet configuration the "baseDir" which is the root
062: * of the file repository:<br>
063: * If not specified the value of "/UserFiles/" will be used.<br>
064: * Also it retrieve all allowed and denied extensions to be handled.
065: *
066: */
067: public void init() throws ServletException {
068:
069: debug = (new Boolean(getInitParameter("debug"))).booleanValue();
070:
071: if (debug)
072: System.out
073: .println("\r\n---- SimpleUploaderServlet initialization started ----");
074:
075: baseDir = getInitParameter("baseDir");
076: enabled = (new Boolean(getInitParameter("enabled")))
077: .booleanValue();
078: if (baseDir == null)
079: baseDir = "/UserFiles/";
080: String realBaseDir = getServletContext().getRealPath(baseDir);
081: File baseFile = new File(realBaseDir);
082: if (!baseFile.exists()) {
083: baseFile.mkdir();
084: }
085:
086: allowedExtensions = new Hashtable(3);
087: deniedExtensions = new Hashtable(3);
088:
089: allowedExtensions
090: .put(
091: "File",
092: stringToArrayList(getInitParameter("AllowedExtensionsFile")));
093: deniedExtensions
094: .put(
095: "File",
096: stringToArrayList(getInitParameter("DeniedExtensionsFile")));
097:
098: allowedExtensions
099: .put(
100: "Image",
101: stringToArrayList(getInitParameter("AllowedExtensionsImage")));
102: deniedExtensions
103: .put(
104: "Image",
105: stringToArrayList(getInitParameter("DeniedExtensionsImage")));
106:
107: allowedExtensions
108: .put(
109: "Flash",
110: stringToArrayList(getInitParameter("AllowedExtensionsFlash")));
111: deniedExtensions
112: .put(
113: "Flash",
114: stringToArrayList(getInitParameter("DeniedExtensionsFlash")));
115:
116: if (debug)
117: System.out
118: .println("---- SimpleUploaderServlet initialization completed ----\r\n");
119:
120: }
121:
122: /**
123: * Manage the Upload requests.<br>
124: *
125: * The servlet accepts commands sent in the following format:<br>
126: * simpleUploader?Type=ResourceType<br>
127: * <br>
128: * It store the file (renaming it in case a file with the same name exists)
129: * and then return an HTML file with a javascript command in it.
130: *
131: */
132: public void doPost(HttpServletRequest request,
133: HttpServletResponse response) throws ServletException,
134: IOException {
135:
136: if (debug)
137: System.out.println("--- BEGIN DOPOST ---");
138:
139: response.setContentType("text/html; charset=UTF-8");
140: response.setHeader("Cache-Control", "no-cache");
141: PrintWriter out = response.getWriter();
142:
143: String typeStr = request.getParameter("Type");
144:
145: String currentPath = baseDir + typeStr;
146: String currentDirPath = getServletContext().getRealPath(
147: currentPath);
148: currentPath = request.getContextPath() + currentPath;
149:
150: if (debug)
151: System.out.println(currentDirPath);
152:
153: String retVal = "0";
154: String newName = "";
155: String fileUrl = "";
156: String errorMessage = "";
157:
158: if (enabled) {
159: DiskFileItemFactory factory = new DiskFileItemFactory();
160: ServletFileUpload upload = new ServletFileUpload(factory);
161: //DiskFileUpload upload = new DiskFileUpload();
162: try {
163: List items = upload.parseRequest(request);
164:
165: Map fields = new HashMap();
166:
167: Iterator iter = items.iterator();
168: while (iter.hasNext()) {
169: FileItem item = (FileItem) iter.next();
170: if (item.isFormField())
171: fields.put(item.getFieldName(), item
172: .getString());
173: else
174: fields.put(item.getFieldName(), item);
175: }
176: FileItem uplFile = (FileItem) fields.get("NewFile");
177: String fileNameLong = uplFile.getName();
178: fileNameLong = fileNameLong.replace('\\', '/');
179: String[] pathParts = fileNameLong.split("/");
180: String fileName = pathParts[pathParts.length - 1];
181:
182: String nameWithoutExt = getNameWithoutExtension(fileName);
183: String ext = getExtension(fileName);
184: File pathToSave = new File(currentDirPath, fileName);
185: fileUrl = currentPath + "/" + fileName;
186: if (extIsAllowed(typeStr, ext)) {
187: int counter = 1;
188: while (pathToSave.exists()) {
189: newName = nameWithoutExt + "(" + counter + ")"
190: + "." + ext;
191: fileUrl = currentPath + "/" + newName;
192: retVal = "201";
193: pathToSave = new File(currentDirPath, newName);
194: counter++;
195: }
196: uplFile.write(pathToSave);
197: } else {
198: retVal = "202";
199: errorMessage = "";
200: if (debug)
201: System.out.println("Invalid file type: " + ext);
202: }
203: } catch (Exception ex) {
204: if (debug)
205: ex.printStackTrace();
206: retVal = "203";
207: }
208: } else {
209: retVal = "1";
210: errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
211: }
212:
213: out.println("<script type=\"text/javascript\">");
214: out.println("window.parent.OnUploadCompleted(" + retVal + ",'"
215: + fileUrl + "','" + newName + "','" + errorMessage
216: + "');");
217: out.println("</script>");
218: out.flush();
219: out.close();
220:
221: if (debug)
222: System.out.println("--- END DOPOST ---");
223:
224: }
225:
226: /*
227: * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF
228: * bug #991489
229: */
230: private static String getNameWithoutExtension(String fileName) {
231: return fileName.substring(0, fileName.lastIndexOf("."));
232: }
233:
234: /*
235: * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF
236: * bug #991489
237: */
238: private String getExtension(String fileName) {
239: return fileName.substring(fileName.lastIndexOf(".") + 1);
240: }
241:
242: /**
243: * Helper function to convert the configuration string to an ArrayList.
244: */
245:
246: private ArrayList stringToArrayList(String str) {
247:
248: if (debug)
249: System.out.println(str);
250: String[] strArr = str.split("\\|");
251:
252: ArrayList tmp = new ArrayList();
253: if (str.length() > 0) {
254: for (int i = 0; i < strArr.length; ++i) {
255: if (debug)
256: System.out.println(i + " - " + strArr[i]);
257: tmp.add(strArr[i].toLowerCase());
258: }
259: }
260: return tmp;
261: }
262:
263: /**
264: * Helper function to verify if a file extension is allowed or not allowed.
265: */
266:
267: private boolean extIsAllowed(String fileType, String ext) {
268:
269: ext = ext.toLowerCase();
270:
271: ArrayList allowList = (ArrayList) allowedExtensions
272: .get(fileType);
273: ArrayList denyList = (ArrayList) deniedExtensions.get(fileType);
274:
275: if (allowList.size() == 0)
276: if (denyList.contains(ext))
277: return false;
278: else
279: return true;
280:
281: if (denyList.size() == 0)
282: if (allowList.contains(ext))
283: return true;
284: else
285: return false;
286:
287: return false;
288: }
289:
290: }
|