001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.upload;
016    
017    import com.liferay.portal.kernel.editor.EditorConstants;
018    import com.liferay.portal.kernel.exception.PortalException;
019    import com.liferay.portal.kernel.exception.SystemException;
020    import com.liferay.portal.kernel.json.JSONFactoryUtil;
021    import com.liferay.portal.kernel.json.JSONObject;
022    import com.liferay.portal.kernel.portlet.JSONPortletResponseUtil;
023    import com.liferay.portal.kernel.repository.model.FileEntry;
024    import com.liferay.portal.kernel.servlet.ServletResponseConstants;
025    import com.liferay.portal.kernel.util.FileUtil;
026    import com.liferay.portal.kernel.util.ParamUtil;
027    import com.liferay.portal.kernel.util.StreamUtil;
028    import com.liferay.portal.kernel.util.StringPool;
029    import com.liferay.portal.kernel.util.WebKeys;
030    import com.liferay.portal.portletfilerepository.PortletFileRepositoryUtil;
031    import com.liferay.portal.security.permission.PermissionChecker;
032    import com.liferay.portal.service.ServiceContext;
033    import com.liferay.portal.theme.ThemeDisplay;
034    import com.liferay.portal.util.PortalUtil;
035    import com.liferay.portlet.documentlibrary.antivirus.AntivirusScannerException;
036    import com.liferay.portlet.documentlibrary.exception.FileNameException;
037    import com.liferay.portlet.documentlibrary.exception.FileSizeException;
038    
039    import java.io.IOException;
040    import java.io.InputStream;
041    
042    import javax.portlet.PortletRequest;
043    import javax.portlet.PortletResponse;
044    
045    /**
046     * @author Sergio Gonz??lez
047     * @author Adolfo P??rez
048     * @author Roberto D??az
049     */
050    public abstract class BaseUploadHandler implements UploadHandler {
051    
052            @Override
053            public void upload(
054                            PortletRequest portletRequest, PortletResponse portletResponse)
055                    throws PortalException {
056    
057                    UploadPortletRequest uploadPortletRequest =
058                            PortalUtil.getUploadPortletRequest(portletRequest);
059    
060                    ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
061                            WebKeys.THEME_DISPLAY);
062    
063                    checkPermission(
064                            themeDisplay.getScopeGroupId(), getFolderId(uploadPortletRequest),
065                            themeDisplay.getPermissionChecker());
066    
067                    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
068    
069                    try {
070                            UploadException uploadException =
071                                    (UploadException)portletRequest.getAttribute(
072                                            WebKeys.UPLOAD_EXCEPTION);
073    
074                            if (uploadException != null) {
075                                    Throwable cause = uploadException.getCause();
076    
077                                    if (uploadException.isExceededFileSizeLimit()) {
078                                            throw new FileSizeException(cause);
079                                    }
080    
081                                    if (uploadException.isExceededLiferayFileItemSizeLimit()) {
082                                            throw new LiferayFileItemException(cause);
083                                    }
084    
085                                    if (uploadException.isExceededUploadRequestSizeLimit()) {
086                                            throw new UploadRequestSizeException(cause);
087                                    }
088    
089                                    throw new PortalException(cause);
090                            }
091    
092                            JSONObject imageJSONObject = getImageJSONObject(portletRequest);
093    
094                            String randomId = ParamUtil.getString(
095                                    uploadPortletRequest, "randomId");
096    
097                            imageJSONObject.put("randomId", randomId);
098    
099                            jsonObject.put("file", imageJSONObject);
100    
101                            jsonObject.put("success", Boolean.TRUE);
102    
103                            JSONPortletResponseUtil.writeJSON(
104                                    portletRequest, portletResponse, jsonObject);
105                    }
106                    catch (IOException ioe) {
107                            throw new SystemException(ioe);
108                    }
109                    catch (PortalException pe) {
110                            handleUploadException(
111                                    portletRequest, portletResponse, pe, jsonObject);
112                    }
113            }
114    
115            protected abstract FileEntry addFileEntry(
116                            long userId, long groupId, long folderId, String fileName,
117                            String contentType, InputStream inputStream, long size,
118                            ServiceContext serviceContext)
119                    throws PortalException;
120    
121            protected abstract void checkPermission(
122                            long groupId, long folderId, PermissionChecker permissionChecker)
123                    throws PortalException;
124    
125            protected void doHandleUploadException(
126                            PortletRequest portletRequest, PortletResponse portletResponse,
127                            PortalException pe, JSONObject jsonObject)
128                    throws PortalException {
129    
130                    throw pe;
131            }
132    
133            protected abstract FileEntry fetchFileEntry(
134                            long userId, long groupId, long folderId, String fileName)
135                    throws PortalException;
136    
137            protected long getFolderId(UploadPortletRequest uploadPortletRequest) {
138                    return 0;
139            }
140    
141            protected JSONObject getImageJSONObject(PortletRequest portletRequest)
142                    throws PortalException {
143    
144                    UploadPortletRequest uploadPortletRequest =
145                            PortalUtil.getUploadPortletRequest(portletRequest);
146    
147                    ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
148                            WebKeys.THEME_DISPLAY);
149    
150                    JSONObject imageJSONObject = JSONFactoryUtil.createJSONObject();
151    
152                    InputStream inputStream = null;
153    
154                    try {
155                            imageJSONObject.put(
156                                    "attributeDataImageId",
157                                    EditorConstants.ATTRIBUTE_DATA_IMAGE_ID);
158    
159                            String parameterName = getParameterName();
160    
161                            String fileName = uploadPortletRequest.getFileName(parameterName);
162                            String contentType = uploadPortletRequest.getContentType(
163                                    parameterName);
164                            long size = uploadPortletRequest.getSize(parameterName);
165    
166                            validateFile(fileName, contentType, size);
167    
168                            long folderId = getFolderId(uploadPortletRequest);
169    
170                            String uniqueFileName = getUniqueFileName(
171                                    themeDisplay, fileName, folderId);
172    
173                            inputStream = uploadPortletRequest.getFileAsStream(parameterName);
174    
175                            FileEntry fileEntry = addFileEntry(
176                                    themeDisplay.getUserId(), themeDisplay.getScopeGroupId(),
177                                    folderId, uniqueFileName, contentType, inputStream, size,
178                                    getServiceContext(uploadPortletRequest));
179    
180                            imageJSONObject.put("fileEntryId", fileEntry.getFileEntryId());
181                            imageJSONObject.put("groupId", fileEntry.getGroupId());
182                            imageJSONObject.put("title", fileEntry.getTitle());
183                            imageJSONObject.put("type", "document");
184                            imageJSONObject.put("url", getURL(fileEntry, themeDisplay));
185                            imageJSONObject.put("uuid", fileEntry.getUuid());
186    
187                            return imageJSONObject;
188                    }
189                    catch (IOException ioe) {
190                            throw new SystemException(ioe);
191                    }
192                    finally {
193                            StreamUtil.cleanUp(inputStream);
194                    }
195            }
196    
197            protected abstract String getParameterName();
198    
199            /**
200             * @throws PortalException
201             */
202            protected ServiceContext getServiceContext(
203                            UploadPortletRequest uploadPortletRequest)
204                    throws PortalException {
205    
206                    return null;
207            }
208    
209            protected String getUniqueFileName(
210                            ThemeDisplay themeDisplay, String fileName, long folderId)
211                    throws PortalException {
212    
213                    FileEntry fileEntry = fetchFileEntry(
214                            themeDisplay.getUserId(), themeDisplay.getScopeGroupId(), folderId,
215                            fileName);
216    
217                    if (fileEntry == null) {
218                            return fileName;
219                    }
220    
221                    int suffix = 1;
222    
223                    for (int i = 0; i < _UNIQUE_FILE_NAME_TRIES; i++) {
224                            String curFileName = FileUtil.appendParentheticalSuffix(
225                                    fileName, String.valueOf(suffix));
226    
227                            fileEntry = fetchFileEntry(
228                                    themeDisplay.getUserId(), themeDisplay.getScopeGroupId(),
229                                    folderId, curFileName);
230    
231                            if (fileEntry == null) {
232                                    return curFileName;
233                            }
234    
235                            suffix++;
236                    }
237    
238                    throw new PortalException(
239                            "Unable to get a unique file name for " + fileName);
240            }
241    
242            protected String getURL(FileEntry fileEntry, ThemeDisplay themeDisplay) {
243                    return PortletFileRepositoryUtil.getPortletFileEntryURL(
244                            themeDisplay, fileEntry, StringPool.BLANK);
245            }
246    
247            protected void handleUploadException(
248                            PortletRequest portletRequest, PortletResponse portletResponse,
249                            PortalException pe, JSONObject jsonObject)
250                    throws PortalException {
251    
252                    jsonObject.put("success", Boolean.FALSE);
253    
254                    if (pe instanceof AntivirusScannerException ||
255                            pe instanceof FileNameException ||
256                            pe instanceof FileSizeException ||
257                            pe instanceof UploadRequestSizeException) {
258    
259                            String errorMessage = StringPool.BLANK;
260                            int errorType = 0;
261    
262                            ThemeDisplay themeDisplay =
263                                    (ThemeDisplay)portletRequest.getAttribute(
264                                            WebKeys.THEME_DISPLAY);
265    
266                            if (pe instanceof AntivirusScannerException) {
267                                    errorType =
268                                            ServletResponseConstants.SC_FILE_ANTIVIRUS_EXCEPTION;
269                                    AntivirusScannerException ase = (AntivirusScannerException)pe;
270    
271                                    errorMessage = themeDisplay.translate(ase.getMessageKey());
272                            }
273                            else if (pe instanceof FileNameException) {
274                                    errorType = ServletResponseConstants.SC_FILE_NAME_EXCEPTION;
275                            }
276                            else if (pe instanceof FileSizeException) {
277                                    errorType = ServletResponseConstants.SC_FILE_SIZE_EXCEPTION;
278                            }
279                            else if (pe instanceof UploadRequestSizeException) {
280                                    errorType =
281                                            ServletResponseConstants.SC_UPLOAD_REQUEST_SIZE_EXCEPTION;
282                            }
283    
284                            JSONObject errorJSONObject = JSONFactoryUtil.createJSONObject();
285    
286                            errorJSONObject.put("errorType", errorType);
287                            errorJSONObject.put("message", errorMessage);
288    
289                            jsonObject.put("error", errorJSONObject);
290                    }
291                    else {
292                            doHandleUploadException(
293                                    portletRequest, portletResponse, pe, jsonObject);
294                    }
295    
296                    try {
297                            JSONPortletResponseUtil.writeJSON(
298                                    portletRequest, portletResponse, jsonObject);
299                    }
300                    catch (IOException ioe) {
301                            throw new SystemException(ioe);
302                    }
303            }
304    
305            protected abstract void validateFile(
306                            String fileName, String contentType, long size)
307                    throws PortalException;
308    
309            protected static final String TEMP_FOLDER_NAME =
310                    BaseUploadHandler.class.getName();
311    
312            private static final int _UNIQUE_FILE_NAME_TRIES = 50;
313    
314    }