1   /**
2    * Copyright (c) 2000-2007 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.editor.fckeditor.receiver.impl;
24  
25  import com.liferay.portal.editor.fckeditor.command.CommandArgument;
26  import com.liferay.portal.editor.fckeditor.exception.FCKException;
27  import com.liferay.portal.editor.fckeditor.receiver.CommandReceiver;
28  import com.liferay.portal.kernel.util.GetterUtil;
29  import com.liferay.portal.kernel.util.StringMaker;
30  import com.liferay.portal.kernel.util.StringPool;
31  import com.liferay.portal.kernel.util.StringUtil;
32  import com.liferay.util.servlet.UploadServletRequest;
33  import com.liferay.util.servlet.fileupload.LiferayFileItemFactory;
34  
35  import java.io.File;
36  import java.io.PrintWriter;
37  
38  import java.util.HashMap;
39  import java.util.Iterator;
40  import java.util.List;
41  import java.util.Map;
42  
43  import javax.servlet.http.HttpServletRequest;
44  import javax.servlet.http.HttpServletResponse;
45  
46  import javax.xml.parsers.DocumentBuilder;
47  import javax.xml.parsers.DocumentBuilderFactory;
48  import javax.xml.parsers.ParserConfigurationException;
49  import javax.xml.transform.Transformer;
50  import javax.xml.transform.TransformerFactory;
51  import javax.xml.transform.dom.DOMSource;
52  import javax.xml.transform.stream.StreamResult;
53  
54  import org.apache.commons.fileupload.FileItem;
55  import org.apache.commons.fileupload.FileUploadException;
56  import org.apache.commons.fileupload.disk.DiskFileItem;
57  import org.apache.commons.fileupload.servlet.ServletFileUpload;
58  import org.apache.commons.logging.Log;
59  import org.apache.commons.logging.LogFactory;
60  
61  import org.w3c.dom.Document;
62  import org.w3c.dom.Element;
63  import org.w3c.dom.Node;
64  
65  /**
66   * <a href="BaseCommandReceiver.java.html"><b><i>View Source</i></b></a>
67   *
68   * @author Ivica Cardic
69   *
70   */
71  public abstract class BaseCommandReceiver implements CommandReceiver {
72  
73      public void createFolder(
74          CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
75  
76          Document doc = _createDocument();
77  
78          Node root = _createRoot(
79              doc, arg.getCommand(), arg.getType(), arg.getCurrentFolder(),
80              "");
81  
82          Element errorEl = doc.createElement("Error");
83  
84          root.appendChild(errorEl);
85  
86          String returnValue = "0";
87  
88          try {
89              returnValue = createFolder(arg);
90          }
91          catch (FCKException fcke) {
92              returnValue = "110";
93          }
94  
95          errorEl.setAttribute("number", returnValue);
96  
97          _writeDocument(doc, res);
98      }
99  
100     public void getFolders(
101         CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
102 
103         Document doc = _createDocument();
104 
105         Node root = _createRoot(
106             doc, arg.getCommand(), arg.getType(), arg.getCurrentFolder(),
107             getPath(arg));
108 
109         getFolders(arg, root, doc);
110 
111         _writeDocument(doc, res);
112     }
113 
114     public void getFoldersAndFiles(
115         CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
116 
117         Document doc = _createDocument();
118 
119         Node root = _createRoot(
120             doc, arg.getCommand(), arg.getType(), arg.getCurrentFolder(),
121             getPath(arg));
122 
123         getFoldersAndFiles(arg, root, doc);
124 
125         _writeDocument(doc, res);
126     }
127 
128     public void fileUpload(
129         CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
130 
131         ServletFileUpload upload = new ServletFileUpload(
132             new LiferayFileItemFactory(UploadServletRequest.DEFAULT_TEMP_DIR));
133 
134         List items = null;
135 
136         try {
137             items = upload.parseRequest(req);
138         }
139         catch (FileUploadException fue) {
140             throw new FCKException(fue);
141         }
142 
143         Map fields = new HashMap();
144 
145         Iterator itr = items.iterator();
146 
147         while (itr.hasNext()) {
148             FileItem item = (FileItem)itr.next();
149 
150             if (item.isFormField()) {
151                 fields.put(item.getFieldName(), item.getString());
152             }
153             else {
154                 fields.put(item.getFieldName(), item);
155             }
156         }
157 
158         DiskFileItem fileItem = (DiskFileItem)fields.get("NewFile");
159 
160         String fileName = StringUtil.replace(fileItem.getName(), "\\", "/");
161         String[] fileNameArray = StringUtil.split(fileName, "/");
162         fileName = fileNameArray[fileNameArray.length - 1];
163 
164         String extension = _getExtension(fileName);
165 
166         String returnValue = null;
167 
168         try {
169             returnValue = fileUpload(
170                 arg, fileName, fileItem.getStoreLocation(), extension);
171         }
172         catch (FCKException fcke) {
173             Throwable cause = fcke.getCause();
174 
175             returnValue = "205";
176 
177             if (cause != null) {
178                 String causeString = GetterUtil.getString(cause.toString());
179 
180                 if ((causeString.indexOf("NoSuchFolderException") != -1) ||
181                     (causeString.indexOf("NoSuchGroupException") != -1)) {
182 
183                     returnValue = "203";
184                 }
185                 else if (causeString.indexOf("ImageNameException") != -1) {
186                     returnValue = "204";
187                 }
188             }
189 
190             _writeUploadResponse(returnValue, res);
191 
192             throw fcke;
193         }
194 
195         _writeUploadResponse(returnValue, res);
196     }
197 
198     protected abstract String createFolder(CommandArgument arg);
199 
200     protected abstract String fileUpload(
201         CommandArgument arg, String fileName, File file, String extension);
202 
203     protected abstract void getFolders(
204         CommandArgument arg, Node root, Document doc);
205 
206     protected abstract void getFoldersAndFiles(
207         CommandArgument arg, Node root, Document doc);
208 
209     protected String getPath(CommandArgument arg) {
210         return StringPool.BLANK;
211     }
212 
213     protected String getSize() {
214         return getSize(0);
215     }
216 
217     protected String getSize(int size) {
218         return String.valueOf(Math.ceil(size / 1000));
219     }
220 
221     private Document _createDocument() {
222         try {
223             Document doc = null;
224 
225             DocumentBuilderFactory factory =
226                 DocumentBuilderFactory.newInstance();
227 
228             DocumentBuilder builder = null;
229 
230             builder = factory.newDocumentBuilder();
231 
232             doc = builder.newDocument();
233 
234             return doc;
235         }
236         catch (ParserConfigurationException pce) {
237             throw new FCKException(pce);
238         }
239     }
240 
241     private Node _createRoot(
242         Document doc, String commandStr, String typeStr, String currentPath,
243         String currentUrl) {
244 
245         Element root = doc.createElement("Connector");
246 
247         doc.appendChild(root);
248 
249         root.setAttribute("command", commandStr);
250         root.setAttribute("resourceType", typeStr);
251 
252         Element el = doc.createElement("CurrentFolder");
253 
254         root.appendChild(el);
255 
256         el.setAttribute("path", currentPath);
257         el.setAttribute("url", currentUrl);
258 
259         return root;
260     }
261 
262     private String _getExtension(String fileName) {
263         return fileName.substring(fileName.lastIndexOf(".") + 1);
264     }
265 
266     private void _writeDocument(Document doc, HttpServletResponse res) {
267         try {
268             doc.getDocumentElement().normalize();
269 
270             TransformerFactory transformerFactory =
271                 TransformerFactory.newInstance();
272 
273             Transformer transformer = transformerFactory.newTransformer();
274 
275             DOMSource source = new DOMSource(doc);
276 
277             if (_log.isDebugEnabled()) {
278                 StreamResult result = new StreamResult(System.out);
279 
280                 transformer.transform(source, result);
281             }
282 
283             res.setContentType("text/xml; charset=UTF-8");
284             res.setHeader("Cache-Control", "no-cache");
285 
286             PrintWriter out = res.getWriter();
287 
288             StreamResult result = new StreamResult(out);
289 
290             transformer.transform(source, result);
291 
292             out.flush();
293             out.close();
294         }
295         catch (Exception e) {
296             throw new FCKException(e);
297         }
298     }
299 
300     private void _writeUploadResponse(
301         String returnValue, HttpServletResponse res) {
302 
303         try {
304             StringMaker sm = new StringMaker();
305 
306             String newName = StringPool.BLANK;
307 
308             sm.append("<script type=\"text/javascript\">");
309             sm.append("window.parent.frames['frmUpload'].OnUploadCompleted(");
310             sm.append(returnValue);
311             sm.append(",'");
312             sm.append(newName);
313             sm.append("');");
314             sm.append("</script>");
315 
316             res.setContentType("text/html; charset=UTF-8");
317             res.setHeader("Cache-Control", "no-cache");
318 
319             PrintWriter out = null;
320 
321             out = res.getWriter();
322 
323             out.print(sm.toString());
324 
325             out.flush();
326             out.close();
327         }
328         catch (Exception e) {
329             throw new FCKException(e);
330         }
331     }
332 
333     private static Log _log = LogFactory.getLog(BaseCommandReceiver.class);
334 
335 }