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