1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
13   */
14  
15  package com.liferay.portal.editor.fckeditor.receiver.impl;
16  
17  import com.liferay.portal.editor.fckeditor.command.CommandArgument;
18  import com.liferay.portal.editor.fckeditor.exception.FCKException;
19  import com.liferay.portal.editor.fckeditor.receiver.CommandReceiver;
20  import com.liferay.portal.kernel.dao.orm.QueryUtil;
21  import com.liferay.portal.kernel.log.Log;
22  import com.liferay.portal.kernel.log.LogFactoryUtil;
23  import com.liferay.portal.kernel.util.CharPool;
24  import com.liferay.portal.kernel.util.GetterUtil;
25  import com.liferay.portal.kernel.util.HtmlUtil;
26  import com.liferay.portal.kernel.util.StringBundler;
27  import com.liferay.portal.kernel.util.StringPool;
28  import com.liferay.portal.kernel.util.StringUtil;
29  import com.liferay.portal.model.Group;
30  import com.liferay.portal.model.Organization;
31  import com.liferay.portal.service.GroupLocalServiceUtil;
32  import com.liferay.portal.service.OrganizationLocalServiceUtil;
33  import com.liferay.portal.theme.ThemeDisplay;
34  import com.liferay.portal.upload.LiferayFileItemFactory;
35  import com.liferay.portal.upload.UploadServletRequestImpl;
36  import com.liferay.portal.util.PropsValues;
37  
38  import java.io.File;
39  import java.io.PrintWriter;
40  
41  import java.util.HashMap;
42  import java.util.LinkedHashMap;
43  import java.util.List;
44  import java.util.Map;
45  
46  import javax.servlet.http.HttpServletRequest;
47  import javax.servlet.http.HttpServletResponse;
48  
49  import javax.xml.parsers.DocumentBuilder;
50  import javax.xml.parsers.DocumentBuilderFactory;
51  import javax.xml.parsers.ParserConfigurationException;
52  import javax.xml.transform.Transformer;
53  import javax.xml.transform.TransformerFactory;
54  import javax.xml.transform.dom.DOMSource;
55  import javax.xml.transform.stream.StreamResult;
56  
57  import org.apache.commons.fileupload.FileItem;
58  import org.apache.commons.fileupload.FileUploadException;
59  import org.apache.commons.fileupload.disk.DiskFileItem;
60  import org.apache.commons.fileupload.servlet.ServletFileUpload;
61  
62  import org.w3c.dom.Document;
63  import org.w3c.dom.Element;
64  import org.w3c.dom.Node;
65  
66  /**
67   * <a href="BaseCommandReceiver.java.html"><b><i>View Source</i></b></a>
68   *
69   * @author Ivica Cardic
70   */
71  public abstract class BaseCommandReceiver implements CommandReceiver {
72  
73      public void createFolder(
74          CommandArgument argument, HttpServletRequest request,
75          HttpServletResponse response) {
76  
77          Document doc = _createDocument();
78  
79          Node root = _createRoot(
80              doc, argument.getCommand(), argument.getType(),
81              argument.getCurrentFolder(), StringPool.BLANK);
82  
83          Element errorEl = doc.createElement("Error");
84  
85          root.appendChild(errorEl);
86  
87          String returnValue = "0";
88  
89          try {
90              returnValue = createFolder(argument);
91          }
92          catch (FCKException fcke) {
93              Throwable cause = fcke.getCause();
94  
95              returnValue = "110";
96  
97              if (cause != null) {
98                  String causeString = GetterUtil.getString(cause.toString());
99  
100                 if (causeString.indexOf("DuplicateFolderNameException") != -1) {
101                     returnValue = "101";
102                 }
103                 else if (causeString.indexOf("FolderNameException") != -1) {
104                     returnValue = "102";
105                 }
106                 else if (causeString.indexOf("NoSuchGroupException") != -1) {
107                     returnValue = "103";
108                 }
109                 else {
110                     throw fcke;
111                 }
112             }
113         }
114 
115         errorEl.setAttribute("number", returnValue);
116 
117         _writeDocument(doc, response);
118     }
119 
120     public void getFolders(
121         CommandArgument argument, HttpServletRequest request,
122         HttpServletResponse response) {
123 
124         Document doc = _createDocument();
125 
126         Node root = _createRoot(
127             doc, argument.getCommand(), argument.getType(),
128             argument.getCurrentFolder(), getPath(argument));
129 
130         getFolders(argument, doc, root);
131 
132         _writeDocument(doc, response);
133     }
134 
135     public void getFoldersAndFiles(
136         CommandArgument argument, HttpServletRequest request,
137         HttpServletResponse response) {
138 
139         Document doc = _createDocument();
140 
141         Node root = _createRoot(
142             doc, argument.getCommand(), argument.getType(),
143             argument.getCurrentFolder(), getPath(argument));
144 
145         getFoldersAndFiles(argument, doc, root);
146 
147         _writeDocument(doc, response);
148     }
149 
150     public void fileUpload(
151         CommandArgument argument, HttpServletRequest request,
152         HttpServletResponse response) {
153 
154         ServletFileUpload upload = new ServletFileUpload(
155             new LiferayFileItemFactory(
156                 UploadServletRequestImpl.DEFAULT_TEMP_DIR));
157 
158         List<FileItem> items = null;
159 
160         try {
161             items = upload.parseRequest(request);
162         }
163         catch (FileUploadException fue) {
164             throw new FCKException(fue);
165         }
166 
167         Map<String, Object> fields = new HashMap<String, Object>();
168 
169         for (FileItem item : items) {
170             if (item.isFormField()) {
171                 fields.put(item.getFieldName(), item.getString());
172             }
173             else {
174                 fields.put(item.getFieldName(), item);
175             }
176         }
177 
178         DiskFileItem fileItem = (DiskFileItem)fields.get("NewFile");
179 
180         String fileName = StringUtil.replace(
181             fileItem.getName(), CharPool.BACK_SLASH, CharPool.SLASH);
182         String[] fileNameArray = StringUtil.split(fileName, "/");
183         fileName = fileNameArray[fileNameArray.length - 1];
184 
185         String extension = _getExtension(fileName);
186 
187         String returnValue = null;
188 
189         try {
190             returnValue = fileUpload(
191                 argument, fileName, fileItem.getStoreLocation(), extension);
192         }
193         catch (FCKException fcke) {
194             Throwable cause = fcke.getCause();
195 
196             returnValue = "203";
197 
198             if (cause != null) {
199                 String causeString = GetterUtil.getString(cause.toString());
200 
201                 if ((causeString.indexOf("NoSuchFolderException") != -1) ||
202                     (causeString.indexOf("NoSuchGroupException") != -1)) {
203 
204                     returnValue = "204";
205                 }
206                 else if (causeString.indexOf("ImageNameException") != -1) {
207                     returnValue = "205";
208                 }
209                 else if (causeString.indexOf("FileNameException") != -1) {
210                     returnValue = "206";
211                 }
212                 else if (causeString.indexOf("PrincipalException") != -1) {
213                     returnValue = "207";
214                 }
215                 else {
216                     throw fcke;
217                 }
218             }
219 
220             _writeUploadResponse(returnValue, response);
221         }
222 
223         _writeUploadResponse(returnValue, response);
224     }
225 
226     protected abstract String createFolder(CommandArgument argument);
227 
228     protected abstract String fileUpload(
229         CommandArgument argument, String fileName, File file, String extension);
230 
231     protected abstract void getFolders(
232         CommandArgument argument, Document doc, Node root);
233 
234     protected abstract void getFoldersAndFiles(
235         CommandArgument argument, Document doc, Node root);
236 
237     protected void getRootFolders(
238             CommandArgument argument, Document doc, Element foldersEl)
239         throws Exception {
240 
241         LinkedHashMap<String, Object> groupParams =
242             new LinkedHashMap<String, Object>();
243 
244         groupParams.put("usersGroups", new Long(argument.getUserId()));
245 
246         List<Group> groups = GroupLocalServiceUtil.search(
247             argument.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS,
248             QueryUtil.ALL_POS);
249 
250         List<Organization> userOrgs =
251             OrganizationLocalServiceUtil.getUserOrganizations(
252                 argument.getUserId(), true);
253 
254         for (Organization organization : userOrgs) {
255             groups.add(0, organization.getGroup());
256         }
257 
258         if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED ||
259             PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) {
260 
261             Group userGroup = GroupLocalServiceUtil.getUserGroup(
262                 argument.getCompanyId(), argument.getUserId());
263 
264             groups.add(0, userGroup);
265         }
266 
267         ThemeDisplay themeDisplay = argument.getThemeDisplay();
268 
269         long scopeGroupId = themeDisplay.getScopeGroupId();
270 
271         for (Group group : groups) {
272             Element folderEl = doc.createElement("Folder");
273 
274             foldersEl.appendChild(folderEl);
275 
276             boolean setNameAttribute = false;
277 
278             if (group.hasStagingGroup()) {
279                 Group stagingGroup = group.getStagingGroup();
280 
281                 if (stagingGroup.getGroupId() == scopeGroupId) {
282                     folderEl.setAttribute(
283                         "name",
284                         stagingGroup.getGroupId() + " - " +
285                             HtmlUtil.escape(stagingGroup.getDescriptiveName()));
286 
287                     setNameAttribute = true;
288                 }
289             }
290 
291             if (!setNameAttribute) {
292                 folderEl.setAttribute(
293                     "name",
294                     group.getGroupId() + " - " +
295                         HtmlUtil.escape(group.getDescriptiveName()));
296             }
297         }
298     }
299 
300     protected String getPath(CommandArgument argument) {
301         return StringPool.BLANK;
302     }
303 
304     protected String getSize() {
305         return getSize(0);
306     }
307 
308     protected String getSize(int size) {
309         return String.valueOf(Math.ceil(size / 1000));
310     }
311 
312     private Document _createDocument() {
313         try {
314             Document doc = null;
315 
316             DocumentBuilderFactory factory =
317                 DocumentBuilderFactory.newInstance();
318 
319             DocumentBuilder builder = null;
320 
321             builder = factory.newDocumentBuilder();
322 
323             doc = builder.newDocument();
324 
325             return doc;
326         }
327         catch (ParserConfigurationException pce) {
328             throw new FCKException(pce);
329         }
330     }
331 
332     private Node _createRoot(
333         Document doc, String commandStr, String typeStr, String currentPath,
334         String currentUrl) {
335 
336         Element root = doc.createElement("Connector");
337 
338         doc.appendChild(root);
339 
340         root.setAttribute("command", commandStr);
341         root.setAttribute("resourceType", typeStr);
342 
343         Element el = doc.createElement("CurrentFolder");
344 
345         root.appendChild(el);
346 
347         el.setAttribute("path", currentPath);
348         el.setAttribute("url", currentUrl);
349 
350         return root;
351     }
352 
353     private String _getExtension(String fileName) {
354         return fileName.substring(fileName.lastIndexOf(CharPool.PERIOD) + 1);
355     }
356 
357     private void _writeDocument(Document doc, HttpServletResponse response) {
358         try {
359             doc.getDocumentElement().normalize();
360 
361             TransformerFactory transformerFactory =
362                 TransformerFactory.newInstance();
363 
364             Transformer transformer = transformerFactory.newTransformer();
365 
366             DOMSource source = new DOMSource(doc);
367 
368             if (_log.isDebugEnabled()) {
369                 StreamResult result = new StreamResult(System.out);
370 
371                 transformer.transform(source, result);
372             }
373 
374             response.setContentType("text/xml; charset=UTF-8");
375             response.setHeader("Cache-Control", "no-cache");
376 
377             PrintWriter out = response.getWriter();
378 
379             StreamResult result = new StreamResult(out);
380 
381             transformer.transform(source, result);
382 
383             out.flush();
384             out.close();
385         }
386         catch (Exception e) {
387             throw new FCKException(e);
388         }
389     }
390 
391     private void _writeUploadResponse(
392         String returnValue, HttpServletResponse response) {
393 
394         try {
395             StringBundler sb = new StringBundler(7);
396 
397             String newName = StringPool.BLANK;
398 
399             sb.append("<script type=\"text/javascript\">");
400             sb.append("window.parent.frames['frmUpload'].OnUploadCompleted(");
401             sb.append(returnValue);
402             sb.append(",'");
403             sb.append(newName);
404             sb.append("');");
405             sb.append("</script>");
406 
407             response.setContentType("text/html; charset=UTF-8");
408             response.setHeader("Cache-Control", "no-cache");
409 
410             PrintWriter out = null;
411 
412             out = response.getWriter();
413 
414             out.print(sb.toString());
415 
416             out.flush();
417             out.close();
418         }
419         catch (Exception e) {
420             throw new FCKException(e);
421         }
422     }
423 
424     private static Log _log = LogFactoryUtil.getLog(BaseCommandReceiver.class);
425 
426 }