1   /**
2    * Copyright (c) 2000-2008 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.portal.model.Group;
33  import com.liferay.portal.model.Organization;
34  import com.liferay.portal.model.User;
35  import com.liferay.portal.service.GroupLocalServiceUtil;
36  import com.liferay.portal.service.UserLocalServiceUtil;
37  import com.liferay.util.dao.hibernate.QueryUtil;
38  import com.liferay.util.servlet.UploadServletRequest;
39  import com.liferay.util.servlet.fileupload.LiferayFileItemFactory;
40  
41  import java.io.File;
42  import java.io.PrintWriter;
43  
44  import java.util.HashMap;
45  import java.util.Iterator;
46  import java.util.LinkedHashMap;
47  import java.util.List;
48  import java.util.Map;
49  
50  import javax.servlet.http.HttpServletRequest;
51  import javax.servlet.http.HttpServletResponse;
52  
53  import javax.xml.parsers.DocumentBuilder;
54  import javax.xml.parsers.DocumentBuilderFactory;
55  import javax.xml.parsers.ParserConfigurationException;
56  import javax.xml.transform.Transformer;
57  import javax.xml.transform.TransformerFactory;
58  import javax.xml.transform.dom.DOMSource;
59  import javax.xml.transform.stream.StreamResult;
60  
61  import org.apache.commons.fileupload.FileItem;
62  import org.apache.commons.fileupload.FileUploadException;
63  import org.apache.commons.fileupload.disk.DiskFileItem;
64  import org.apache.commons.fileupload.servlet.ServletFileUpload;
65  import org.apache.commons.logging.Log;
66  import org.apache.commons.logging.LogFactory;
67  
68  import org.w3c.dom.Document;
69  import org.w3c.dom.Element;
70  import org.w3c.dom.Node;
71  
72  /**
73   * <a href="BaseCommandReceiver.java.html"><b><i>View Source</i></b></a>
74   *
75   * @author Ivica Cardic
76   *
77   */
78  public abstract class BaseCommandReceiver implements CommandReceiver {
79  
80      public void createFolder(
81          CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
82  
83          Document doc = _createDocument();
84  
85          Node root = _createRoot(
86              doc, arg.getCommand(), arg.getType(), arg.getCurrentFolder(),
87              "");
88  
89          Element errorEl = doc.createElement("Error");
90  
91          root.appendChild(errorEl);
92  
93          String returnValue = "0";
94  
95          try {
96              returnValue = createFolder(arg);
97          }
98          catch (FCKException fcke) {
99              returnValue = "110";
100         }
101 
102         errorEl.setAttribute("number", returnValue);
103 
104         _writeDocument(doc, res);
105     }
106 
107     public void getFolders(
108         CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
109 
110         Document doc = _createDocument();
111 
112         Node root = _createRoot(
113             doc, arg.getCommand(), arg.getType(), arg.getCurrentFolder(),
114             getPath(arg));
115 
116         getFolders(arg, doc, root);
117 
118         _writeDocument(doc, res);
119     }
120 
121     public void getFoldersAndFiles(
122         CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
123 
124         Document doc = _createDocument();
125 
126         Node root = _createRoot(
127             doc, arg.getCommand(), arg.getType(), arg.getCurrentFolder(),
128             getPath(arg));
129 
130         getFoldersAndFiles(arg, doc, root);
131 
132         _writeDocument(doc, res);
133     }
134 
135     public void fileUpload(
136         CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
137 
138         ServletFileUpload upload = new ServletFileUpload(
139             new LiferayFileItemFactory(UploadServletRequest.DEFAULT_TEMP_DIR));
140 
141         List items = null;
142 
143         try {
144             items = upload.parseRequest(req);
145         }
146         catch (FileUploadException fue) {
147             throw new FCKException(fue);
148         }
149 
150         Map fields = new HashMap();
151 
152         Iterator itr = items.iterator();
153 
154         while (itr.hasNext()) {
155             FileItem item = (FileItem)itr.next();
156 
157             if (item.isFormField()) {
158                 fields.put(item.getFieldName(), item.getString());
159             }
160             else {
161                 fields.put(item.getFieldName(), item);
162             }
163         }
164 
165         DiskFileItem fileItem = (DiskFileItem)fields.get("NewFile");
166 
167         String fileName = StringUtil.replace(fileItem.getName(), "\\", "/");
168         String[] fileNameArray = StringUtil.split(fileName, "/");
169         fileName = fileNameArray[fileNameArray.length - 1];
170 
171         String extension = _getExtension(fileName);
172 
173         String returnValue = null;
174 
175         try {
176             returnValue = fileUpload(
177                 arg, fileName, fileItem.getStoreLocation(), extension);
178         }
179         catch (FCKException fcke) {
180             Throwable cause = fcke.getCause();
181 
182             returnValue = "205";
183 
184             if (cause != null) {
185                 String causeString = GetterUtil.getString(cause.toString());
186 
187                 if ((causeString.indexOf("NoSuchFolderException") != -1) ||
188                     (causeString.indexOf("NoSuchGroupException") != -1)) {
189 
190                     returnValue = "203";
191                 }
192                 else if (causeString.indexOf("ImageNameException") != -1) {
193                     returnValue = "204";
194                 }
195             }
196 
197             _writeUploadResponse(returnValue, res);
198 
199             throw fcke;
200         }
201 
202         _writeUploadResponse(returnValue, res);
203     }
204 
205     protected abstract String createFolder(CommandArgument arg);
206 
207     protected abstract String fileUpload(
208         CommandArgument arg, String fileName, File file, String extension);
209 
210     protected abstract void getFolders(
211         CommandArgument arg, Document doc, Node root);
212 
213     protected abstract void getFoldersAndFiles(
214         CommandArgument arg, Document doc, Node root);
215 
216     protected void getRootFolders(
217             CommandArgument arg, Document doc, Element foldersEl)
218         throws Exception {
219 
220         LinkedHashMap groupParams = new LinkedHashMap();
221 
222         groupParams.put("usersGroups", new Long(arg.getUserId()));
223 
224         List groups = GroupLocalServiceUtil.search(
225             arg.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS,
226             QueryUtil.ALL_POS);
227 
228         User user = UserLocalServiceUtil.getUserById(arg.getUserId());
229 
230         List userOrgs = user.getOrganizations();
231 
232         Iterator itr = userOrgs.iterator();
233 
234         while (itr.hasNext()) {
235             Organization organization = (Organization)itr.next();
236 
237             groups.add(0, organization.getGroup());
238         }
239 
240         if (user.isLayoutsRequired()) {
241             Group userGroup = user.getGroup();
242 
243             groups.add(0, userGroup);
244         }
245 
246         for (int i = 0; i < groups.size(); ++i) {
247             Group group = (Group)groups.get(i);
248 
249             Element folderEl = doc.createElement("Folder");
250 
251             foldersEl.appendChild(folderEl);
252 
253             folderEl.setAttribute(
254                 "name",
255                 group.getGroupId() + " - " + group.getDescriptiveName());
256         }
257     }
258 
259     protected String getPath(CommandArgument arg) {
260         return StringPool.BLANK;
261     }
262 
263     protected String getSize() {
264         return getSize(0);
265     }
266 
267     protected String getSize(int size) {
268         return String.valueOf(Math.ceil(size / 1000));
269     }
270 
271     private Document _createDocument() {
272         try {
273             Document doc = null;
274 
275             DocumentBuilderFactory factory =
276                 DocumentBuilderFactory.newInstance();
277 
278             DocumentBuilder builder = null;
279 
280             builder = factory.newDocumentBuilder();
281 
282             doc = builder.newDocument();
283 
284             return doc;
285         }
286         catch (ParserConfigurationException pce) {
287             throw new FCKException(pce);
288         }
289     }
290 
291     private Node _createRoot(
292         Document doc, String commandStr, String typeStr, String currentPath,
293         String currentUrl) {
294 
295         Element root = doc.createElement("Connector");
296 
297         doc.appendChild(root);
298 
299         root.setAttribute("command", commandStr);
300         root.setAttribute("resourceType", typeStr);
301 
302         Element el = doc.createElement("CurrentFolder");
303 
304         root.appendChild(el);
305 
306         el.setAttribute("path", currentPath);
307         el.setAttribute("url", currentUrl);
308 
309         return root;
310     }
311 
312     private String _getExtension(String fileName) {
313         return fileName.substring(fileName.lastIndexOf(".") + 1);
314     }
315 
316     private void _writeDocument(Document doc, HttpServletResponse res) {
317         try {
318             doc.getDocumentElement().normalize();
319 
320             TransformerFactory transformerFactory =
321                 TransformerFactory.newInstance();
322 
323             Transformer transformer = transformerFactory.newTransformer();
324 
325             DOMSource source = new DOMSource(doc);
326 
327             if (_log.isDebugEnabled()) {
328                 StreamResult result = new StreamResult(System.out);
329 
330                 transformer.transform(source, result);
331             }
332 
333             res.setContentType("text/xml; charset=UTF-8");
334             res.setHeader("Cache-Control", "no-cache");
335 
336             PrintWriter out = res.getWriter();
337 
338             StreamResult result = new StreamResult(out);
339 
340             transformer.transform(source, result);
341 
342             out.flush();
343             out.close();
344         }
345         catch (Exception e) {
346             throw new FCKException(e);
347         }
348     }
349 
350     private void _writeUploadResponse(
351         String returnValue, HttpServletResponse res) {
352 
353         try {
354             StringMaker sm = new StringMaker();
355 
356             String newName = StringPool.BLANK;
357 
358             sm.append("<script type=\"text/javascript\">");
359             sm.append("window.parent.frames['frmUpload'].OnUploadCompleted(");
360             sm.append(returnValue);
361             sm.append(",'");
362             sm.append(newName);
363             sm.append("');");
364             sm.append("</script>");
365 
366             res.setContentType("text/html; charset=UTF-8");
367             res.setHeader("Cache-Control", "no-cache");
368 
369             PrintWriter out = null;
370 
371             out = res.getWriter();
372 
373             out.print(sm.toString());
374 
375             out.flush();
376             out.close();
377         }
378         catch (Exception e) {
379             throw new FCKException(e);
380         }
381     }
382 
383     private static Log _log = LogFactory.getLog(BaseCommandReceiver.class);
384 
385 }