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