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.FileNameException;
036    import com.liferay.portlet.documentlibrary.FileSizeException;
037    import com.liferay.portlet.documentlibrary.antivirus.AntivirusScannerException;
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                    UploadException uploadException =
068                            (UploadException)portletRequest.getAttribute(
069                                    WebKeys.UPLOAD_EXCEPTION);
070    
071                    if (uploadException != null) {
072                            if (uploadException.isExceededLiferayFileItemSizeLimit()) {
073                                    throw new LiferayFileItemException();
074                            }
075                            else if (uploadException.isExceededSizeLimit()) {
076                                    throw new FileSizeException(uploadException.getCause());
077                            }
078    
079                            throw new PortalException(uploadException.getCause());
080                    }
081    
082                    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
083    
084                    String randomId = ParamUtil.getString(uploadPortletRequest, "randomId");
085    
086                    try {
087                            JSONObject imageJSONObject = getImageJSONObject(portletRequest);
088    
089                            jsonObject.put("success", Boolean.TRUE);
090    
091                            imageJSONObject.put("randomId", randomId);
092    
093                            jsonObject.put("file", imageJSONObject);
094    
095                            JSONPortletResponseUtil.writeJSON(
096                                    portletRequest, portletResponse, jsonObject);
097                    }
098                    catch (IOException ioe) {
099                            throw new SystemException(ioe);
100                    }
101                    catch (PortalException pe) {
102                            handleUploadException(
103                                    portletRequest, portletResponse, pe, jsonObject);
104                    }
105            }
106    
107            protected abstract FileEntry addFileEntry(
108                            long userId, long groupId, long folderId, String fileName,
109                            String contentType, InputStream inputStream, long size,
110                            ServiceContext serviceContext)
111                    throws PortalException;
112    
113            protected abstract void checkPermission(
114                            long groupId, long folderId, PermissionChecker permissionChecker)
115                    throws PortalException;
116    
117            protected abstract void doHandleUploadException(
118                            PortletRequest portletRequest, PortletResponse portletResponse,
119                            PortalException pe, JSONObject jsonObject)
120                    throws PortalException;
121    
122            protected abstract FileEntry fetchFileEntry(
123                            long userId, long groupId, long folderId, String fileName)
124                    throws PortalException;
125    
126            protected long getFolderId(UploadPortletRequest uploadPortletRequest) {
127                    return 0;
128            }
129    
130            protected JSONObject getImageJSONObject(PortletRequest portletRequest)
131                    throws PortalException {
132    
133                    UploadPortletRequest uploadPortletRequest =
134                            PortalUtil.getUploadPortletRequest(portletRequest);
135    
136                    ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
137                            WebKeys.THEME_DISPLAY);
138    
139                    JSONObject imageJSONObject = JSONFactoryUtil.createJSONObject();
140    
141                    InputStream inputStream = null;
142    
143                    try {
144                            imageJSONObject.put(
145                                    "attributeDataImageId",
146                                    EditorConstants.ATTRIBUTE_DATA_IMAGE_ID);
147    
148                            String parameterName = getParameterName();
149    
150                            String fileName = uploadPortletRequest.getFileName(parameterName);
151                            String contentType = uploadPortletRequest.getContentType(
152                                    parameterName);
153                            long size = uploadPortletRequest.getSize(parameterName);
154    
155                            validateFile(fileName, contentType, size);
156    
157                            long folderId = getFolderId(uploadPortletRequest);
158    
159                            String uniqueFileName = getUniqueFileName(
160                                    themeDisplay, fileName, folderId);
161    
162                            inputStream = uploadPortletRequest.getFileAsStream(parameterName);
163    
164                            FileEntry fileEntry = addFileEntry(
165                                    themeDisplay.getUserId(), themeDisplay.getScopeGroupId(),
166                                    folderId, uniqueFileName, contentType, inputStream, size,
167                                    getServiceContext(uploadPortletRequest));
168    
169                            imageJSONObject.put("fileEntryId", fileEntry.getFileEntryId());
170                            imageJSONObject.put("groupId", fileEntry.getGroupId());
171                            imageJSONObject.put("title", fileEntry.getTitle());
172                            imageJSONObject.put("url", getURL(fileEntry, themeDisplay));
173                            imageJSONObject.put("uuid", fileEntry.getUuid());
174    
175                            return imageJSONObject;
176                    }
177                    catch (IOException ioe) {
178                            throw new SystemException(ioe);
179                    }
180                    finally {
181                            StreamUtil.cleanUp(inputStream);
182                    }
183            }
184    
185            protected abstract String getParameterName();
186    
187            /**
188             * @throws PortalException
189             */
190            protected ServiceContext getServiceContext(
191                            UploadPortletRequest uploadPortletRequest)
192                    throws PortalException {
193    
194                    return null;
195            }
196    
197            protected String getUniqueFileName(
198                            ThemeDisplay themeDisplay, String fileName, long folderId)
199                    throws PortalException {
200    
201                    FileEntry fileEntry = fetchFileEntry(
202                            themeDisplay.getUserId(), themeDisplay.getScopeGroupId(), folderId,
203                            fileName);
204    
205                    if (fileEntry == null) {
206                            return fileName;
207                    }
208    
209                    int suffix = 1;
210    
211                    for (int i = 0; i < _UNIQUE_FILE_NAME_TRIES; i++) {
212                            String curFileName = FileUtil.appendParentheticalSuffix(
213                                    fileName, String.valueOf(suffix));
214    
215                            fileEntry = fetchFileEntry(
216                                    themeDisplay.getUserId(), themeDisplay.getScopeGroupId(),
217                                    folderId, curFileName);
218    
219                            if (fileEntry == null) {
220                                    return curFileName;
221                            }
222    
223                            suffix++;
224                    }
225    
226                    throw new PortalException(
227                            "Unable to get a unique file name for " + fileName);
228            }
229    
230            protected String getURL(FileEntry fileEntry, ThemeDisplay themeDisplay) {
231                    return PortletFileRepositoryUtil.getPortletFileEntryURL(
232                            themeDisplay, fileEntry, StringPool.BLANK);
233            }
234    
235            protected void handleUploadException(
236                            PortletRequest portletRequest, PortletResponse portletResponse,
237                            PortalException pe, JSONObject jsonObject)
238                    throws PortalException {
239    
240                    jsonObject.put("success", Boolean.FALSE);
241    
242                    if (pe instanceof AntivirusScannerException ||
243                            pe instanceof FileNameException) {
244    
245                            String errorMessage = StringPool.BLANK;
246                            int errorType = 0;
247    
248                            ThemeDisplay themeDisplay =
249                                    (ThemeDisplay)portletRequest.getAttribute(
250                                            WebKeys.THEME_DISPLAY);
251    
252                            if (pe instanceof AntivirusScannerException) {
253                                    errorType =
254                                            ServletResponseConstants.SC_FILE_ANTIVIRUS_EXCEPTION;
255                                    AntivirusScannerException ase = (AntivirusScannerException)pe;
256    
257                                    errorMessage = themeDisplay.translate(ase.getMessageKey());
258                            }
259                            else if (pe instanceof FileNameException) {
260                                    errorType = ServletResponseConstants.SC_FILE_NAME_EXCEPTION;
261                            }
262    
263                            JSONObject errorJSONObject = JSONFactoryUtil.createJSONObject();
264    
265                            errorJSONObject.put("errorType", errorType);
266                            errorJSONObject.put("message", errorMessage);
267    
268                            jsonObject.put("error", errorJSONObject);
269                    }
270                    else {
271                            doHandleUploadException(
272                                    portletRequest, portletResponse, pe, jsonObject);
273                    }
274    
275                    try {
276                            JSONPortletResponseUtil.writeJSON(
277                                    portletRequest, portletResponse, jsonObject);
278                    }
279                    catch (IOException ioe) {
280                            throw new SystemException(ioe);
281                    }
282            }
283    
284            protected abstract void validateFile(
285                            String fileName, String contentType, long size)
286                    throws PortalException;
287    
288            protected static final String TEMP_FOLDER_NAME =
289                    BaseUploadHandler.class.getName();
290    
291            private static final int _UNIQUE_FILE_NAME_TRIES = 50;
292    
293    }