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