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: ConnectorServlet.java
012: * Java Connector for Resource Manager 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 com.fredck.FCKeditor.connector;
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.*;
029:
030: import javax.xml.parsers.*;
031: import org.w3c.dom.*;
032: import javax.xml.transform.*;
033: import javax.xml.transform.dom.DOMSource;
034: import javax.xml.transform.stream.StreamResult;
035:
036: import com.Yasna.forum.Authorization;
037: import com.Yasna.forum.util.SkinUtils;
038:
039: /**
040: * Servlet to upload and browse files.<br>
041: *
042: * This servlet accepts 4 commands used to retrieve and create files and folders from a server directory.
043: * The allowed commands are:
044: * <ul>
045: * <li>GetFolders: Retrive the list of directory under the current folder
046: * <li>GetFoldersAndFiles: Retrive the list of files and directory under the current folder
047: * <li>CreateFolder: Create a new directory under the current folder
048: * <li>FileUpload: Send a new file to the server (must be sent with a POST)
049: * </ul>
050: *
051: * @author Simone Chiaretta (simo@users.sourceforge.net)
052: */
053:
054: public class ConnectorServlet extends HttpServlet {
055:
056: private static String baseDir;
057: private static boolean debug = false;
058:
059: /**
060: * Initialize the servlet.<br>
061: * Retrieve from the servlet configuration the "baseDir" which is the root of the file repository:<br>
062: * If not specified the value of "/UserFiles/" will be used.
063: *
064: */
065: public void init() throws ServletException {
066: baseDir = getInitParameter("baseDir");
067: debug = (new Boolean(getInitParameter("debug"))).booleanValue();
068: if (baseDir == null)
069: baseDir = "/UserFiles/";
070: String realBaseDir = getServletContext().getRealPath(baseDir);
071: File baseFile = new File(realBaseDir);
072: if (!baseFile.exists()) {
073: baseFile.mkdir();
074: }
075: }
076:
077: /**
078: * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br>
079: *
080: * The servlet accepts commands sent in the following format:<br>
081: * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br><br>
082: * It execute the command and then return the results to the client in XML format.
083: *
084: */
085: public void doGet(HttpServletRequest request,
086: HttpServletResponse response) throws ServletException,
087: IOException {
088:
089: if (debug)
090: System.out.println("--- BEGIN DOGET ---");
091:
092: response.setContentType("text/xml; charset=UTF-8");
093: response.setHeader("Cache-Control", "no-cache");
094: PrintWriter out = response.getWriter();
095:
096: Authorization authToken = SkinUtils.getUserAuthorization(
097: request, response);
098: String userdir = request.getRemoteAddr();
099: if (authToken != null) {
100: userdir = Integer.toString(authToken.getUserID());
101: }
102: String realBaseDir = getServletContext().getRealPath(
103: baseDir + userdir);
104: File baseFile = new File(realBaseDir);
105: if (!baseFile.exists()) {
106: baseFile.mkdir();
107: }
108:
109: String commandStr = request.getParameter("Command");
110: String typeStr = request.getParameter("Type");
111: String currentFolderStr = request.getParameter("CurrentFolder");
112:
113: String currentPath = baseDir + userdir + "/" + typeStr
114: + currentFolderStr;
115: String currentDirPath = getServletContext().getRealPath(
116: currentPath);
117:
118: File currentDir = new File(currentDirPath);
119: if (!currentDir.exists()) {
120: currentDir.mkdir();
121: }
122:
123: Document document = null;
124: try {
125: DocumentBuilderFactory factory = DocumentBuilderFactory
126: .newInstance();
127: DocumentBuilder builder = factory.newDocumentBuilder();
128: document = builder.newDocument();
129: } catch (ParserConfigurationException pce) {
130: pce.printStackTrace();
131: }
132:
133: Node root = CreateCommonXml(document, commandStr, typeStr,
134: currentFolderStr, request.getContextPath()
135: + currentPath);
136:
137: if (debug)
138: System.out.println("Command = " + commandStr);
139:
140: if (commandStr.equals("GetFolders")) {
141: getFolders(currentDir, root, document);
142: } else if (commandStr.equals("GetFoldersAndFiles")) {
143: getFolders(currentDir, root, document);
144: getFiles(currentDir, root, document);
145: } else if (commandStr.equals("CreateFolder")) {
146: String newFolderStr = request.getParameter("NewFolderName");
147: File newFolder = new File(currentDir, newFolderStr);
148: String retValue = "110";
149:
150: if (newFolder.exists()) {
151: retValue = "101";
152: } else {
153: try {
154: boolean dirCreated = newFolder.mkdir();
155: if (dirCreated)
156: retValue = "0";
157: else
158: retValue = "102";
159: } catch (SecurityException sex) {
160: retValue = "103";
161: }
162:
163: }
164: setCreateFolderResponse(retValue, root, document);
165: }
166:
167: document.getDocumentElement().normalize();
168: try {
169: TransformerFactory tFactory = TransformerFactory
170: .newInstance();
171: Transformer transformer = tFactory.newTransformer();
172:
173: DOMSource source = new DOMSource(document);
174:
175: StreamResult result = new StreamResult(out);
176: transformer.transform(source, result);
177:
178: if (debug) {
179: StreamResult dbgResult = new StreamResult(System.out);
180: transformer.transform(source, dbgResult);
181: System.out.println("");
182: System.out.println("--- END DOGET ---");
183: }
184:
185: } catch (Exception ex) {
186: ex.printStackTrace();
187: }
188:
189: out.flush();
190: out.close();
191: }
192:
193: /**
194: * Manage the Post requests (FileUpload).<br>
195: *
196: * The servlet accepts commands sent in the following format:<br>
197: * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br>
198: * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
199: * with a javascript command in it.
200: *
201: */
202: public void doPost(HttpServletRequest request,
203: HttpServletResponse response) throws ServletException,
204: IOException {
205:
206: if (debug)
207: System.out.println("--- BEGIN DOPOST ---");
208: Authorization authToken = SkinUtils.getUserAuthorization(
209: request, response);
210: String userdir = request.getRemoteAddr();
211: if (authToken != null) {
212: userdir = Integer.toString(authToken.getUserID());
213: }
214: String realBaseDir = getServletContext().getRealPath(
215: baseDir + userdir);
216: File baseFile = new File(realBaseDir);
217: if (!baseFile.exists()) {
218: baseFile.mkdir();
219: }
220:
221: response.setContentType("text/html; charset=UTF-8");
222: response.setHeader("Cache-Control", "no-cache");
223: PrintWriter out = response.getWriter();
224:
225: String commandStr = request.getParameter("Command");
226: String typeStr = request.getParameter("Type");
227: String currentFolderStr = request.getParameter("CurrentFolder");
228:
229: String currentPath = baseDir + userdir + "/" + typeStr
230: + currentFolderStr;
231: String currentDirPath = getServletContext().getRealPath(
232: currentPath);
233:
234: if (debug)
235: System.out.println(currentDirPath);
236:
237: String retVal = "0";
238: String newName = "";
239:
240: if (!commandStr.equals("FileUpload"))
241: retVal = "203";
242: else {
243: DiskFileUpload upload = new DiskFileUpload();
244: try {
245: List items = upload.parseRequest(request);
246:
247: Map fields = new HashMap();
248:
249: Iterator iter = items.iterator();
250: while (iter.hasNext()) {
251: FileItem item = (FileItem) iter.next();
252: if (item.isFormField())
253: fields.put(item.getFieldName(), item
254: .getString());
255: else
256: fields.put(item.getFieldName(), item);
257: }
258: FileItem uplFile = (FileItem) fields.get("NewFile");
259: String fileNameLong = uplFile.getName();
260: fileNameLong = fileNameLong.replace('\\', '/');
261: String[] pathParts = fileNameLong.split("/");
262: String fileName = pathParts[pathParts.length - 1];
263:
264: String nameWithoutExt = getNameWithoutExtension(fileName);
265: String ext = getExtension(fileName);
266: File pathToSave = new File(currentDirPath, fileName);
267: int counter = 1;
268: while (pathToSave.exists()) {
269: newName = nameWithoutExt + "(" + counter + ")"
270: + "." + ext;
271: retVal = "201";
272: pathToSave = new File(currentDirPath, newName);
273: counter++;
274: }
275: uplFile.write(pathToSave);
276: } catch (Exception ex) {
277: retVal = "203";
278: }
279:
280: }
281:
282: out.println("<script type=\"text/javascript\">");
283: out
284: .println("window.parent.frames['frmUpload'].OnUploadCompleted("
285: + retVal + ",'" + newName + "');");
286: out.println("</script>");
287: out.flush();
288: out.close();
289:
290: if (debug)
291: System.out.println("--- END DOPOST ---");
292:
293: }
294:
295: private void setCreateFolderResponse(String retValue, Node root,
296: Document doc) {
297: Element myEl = doc.createElement("Error");
298: myEl.setAttribute("number", retValue);
299: root.appendChild(myEl);
300: }
301:
302: private void getFolders(File dir, Node root, Document doc) {
303: Element folders = doc.createElement("Folders");
304: root.appendChild(folders);
305: File[] fileList = dir.listFiles();
306: for (int i = 0; i < fileList.length; ++i) {
307: if (fileList[i].isDirectory()) {
308: Element myEl = doc.createElement("Folder");
309: myEl.setAttribute("name", fileList[i].getName());
310: folders.appendChild(myEl);
311: }
312: }
313: }
314:
315: private void getFiles(File dir, Node root, Document doc) {
316: Element files = doc.createElement("Files");
317: root.appendChild(files);
318: File[] fileList = dir.listFiles();
319: for (int i = 0; i < fileList.length; ++i) {
320: if (fileList[i].isFile()) {
321: Element myEl = doc.createElement("File");
322: myEl.setAttribute("name", fileList[i].getName());
323: myEl.setAttribute("size", "" + fileList[i].length()
324: / 1024);
325: files.appendChild(myEl);
326: }
327: }
328: }
329:
330: private Node CreateCommonXml(Document doc, String commandStr,
331: String typeStr, String currentPath, String currentUrl) {
332:
333: Element root = doc.createElement("Connector");
334: doc.appendChild(root);
335: root.setAttribute("command", commandStr);
336: root.setAttribute("resourceType", typeStr);
337:
338: Element myEl = doc.createElement("CurrentFolder");
339: myEl.setAttribute("path", currentPath);
340: myEl.setAttribute("url", currentUrl);
341: root.appendChild(myEl);
342:
343: return root;
344:
345: }
346:
347: /*
348: * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF bug #991489
349: */
350: private static String getNameWithoutExtension(String fileName) {
351: return fileName.substring(0, fileName.lastIndexOf("."));
352: }
353:
354: /*
355: * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF bug #991489
356: */
357: private String getExtension(String fileName) {
358: return fileName.substring(fileName.lastIndexOf(".") + 1);
359: }
360:
361: }
|