001    /**
002     * Copyright (c) 2000-2013 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.portlet.documentlibrary.action;
016    
017    import com.liferay.portal.DuplicateLockException;
018    import com.liferay.portal.NoSuchRepositoryEntryException;
019    import com.liferay.portal.kernel.exception.PortalException;
020    import com.liferay.portal.kernel.exception.SystemException;
021    import com.liferay.portal.kernel.json.JSONArray;
022    import com.liferay.portal.kernel.json.JSONFactoryUtil;
023    import com.liferay.portal.kernel.json.JSONObject;
024    import com.liferay.portal.kernel.portlet.LiferayWindowState;
025    import com.liferay.portal.kernel.repository.model.FileEntry;
026    import com.liferay.portal.kernel.repository.model.Folder;
027    import com.liferay.portal.kernel.servlet.ServletResponseConstants;
028    import com.liferay.portal.kernel.servlet.SessionErrors;
029    import com.liferay.portal.kernel.servlet.SessionMessages;
030    import com.liferay.portal.kernel.upload.LiferayFileItemException;
031    import com.liferay.portal.kernel.upload.UploadException;
032    import com.liferay.portal.kernel.upload.UploadPortletRequest;
033    import com.liferay.portal.kernel.util.Constants;
034    import com.liferay.portal.kernel.util.ContentTypes;
035    import com.liferay.portal.kernel.util.FileUtil;
036    import com.liferay.portal.kernel.util.HttpUtil;
037    import com.liferay.portal.kernel.util.KeyValuePair;
038    import com.liferay.portal.kernel.util.MimeTypesUtil;
039    import com.liferay.portal.kernel.util.ParamUtil;
040    import com.liferay.portal.kernel.util.PropsKeys;
041    import com.liferay.portal.kernel.util.StreamUtil;
042    import com.liferay.portal.kernel.util.StringBundler;
043    import com.liferay.portal.kernel.util.StringPool;
044    import com.liferay.portal.kernel.util.StringUtil;
045    import com.liferay.portal.kernel.util.TempFileUtil;
046    import com.liferay.portal.kernel.util.Validator;
047    import com.liferay.portal.kernel.workflow.WorkflowConstants;
048    import com.liferay.portal.security.auth.PrincipalException;
049    import com.liferay.portal.service.ServiceContext;
050    import com.liferay.portal.service.ServiceContextFactory;
051    import com.liferay.portal.struts.ActionConstants;
052    import com.liferay.portal.struts.PortletAction;
053    import com.liferay.portal.theme.ThemeDisplay;
054    import com.liferay.portal.util.PortalUtil;
055    import com.liferay.portal.util.PortletKeys;
056    import com.liferay.portal.util.PrefsPropsUtil;
057    import com.liferay.portal.util.WebKeys;
058    import com.liferay.portlet.PortletURLImpl;
059    import com.liferay.portlet.asset.AssetCategoryException;
060    import com.liferay.portlet.asset.AssetTagException;
061    import com.liferay.portlet.asset.model.AssetVocabulary;
062    import com.liferay.portlet.assetpublisher.util.AssetPublisherUtil;
063    import com.liferay.portlet.documentlibrary.DuplicateFileException;
064    import com.liferay.portlet.documentlibrary.DuplicateFolderNameException;
065    import com.liferay.portlet.documentlibrary.FileExtensionException;
066    import com.liferay.portlet.documentlibrary.FileMimeTypeException;
067    import com.liferay.portlet.documentlibrary.FileNameException;
068    import com.liferay.portlet.documentlibrary.FileSizeException;
069    import com.liferay.portlet.documentlibrary.InvalidFileEntryTypeException;
070    import com.liferay.portlet.documentlibrary.InvalidFileVersionException;
071    import com.liferay.portlet.documentlibrary.NoSuchFileEntryException;
072    import com.liferay.portlet.documentlibrary.NoSuchFileVersionException;
073    import com.liferay.portlet.documentlibrary.NoSuchFolderException;
074    import com.liferay.portlet.documentlibrary.SourceFileNameException;
075    import com.liferay.portlet.documentlibrary.antivirus.AntivirusScannerException;
076    import com.liferay.portlet.documentlibrary.model.DLFileEntry;
077    import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
078    import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil;
079    import com.liferay.portlet.documentlibrary.util.DLUtil;
080    import com.liferay.portlet.dynamicdatamapping.StorageFieldRequiredException;
081    import com.liferay.portlet.trash.util.TrashUtil;
082    
083    import java.io.InputStream;
084    
085    import java.util.ArrayList;
086    import java.util.Arrays;
087    import java.util.HashMap;
088    import java.util.HashSet;
089    import java.util.List;
090    import java.util.Map;
091    import java.util.Set;
092    
093    import javax.portlet.ActionRequest;
094    import javax.portlet.ActionResponse;
095    import javax.portlet.PortletConfig;
096    import javax.portlet.PortletContext;
097    import javax.portlet.PortletPreferences;
098    import javax.portlet.PortletRequest;
099    import javax.portlet.PortletRequestDispatcher;
100    import javax.portlet.PortletResponse;
101    import javax.portlet.RenderRequest;
102    import javax.portlet.RenderResponse;
103    import javax.portlet.ResourceRequest;
104    import javax.portlet.ResourceResponse;
105    import javax.portlet.WindowState;
106    
107    import javax.servlet.http.HttpServletResponse;
108    
109    import org.apache.commons.fileupload.FileUploadBase.IOFileUploadException;
110    import org.apache.struts.action.ActionForm;
111    import org.apache.struts.action.ActionForward;
112    import org.apache.struts.action.ActionMapping;
113    
114    /**
115     * @author Brian Wing Shun Chan
116     * @author Alexander Chow
117     * @author Sergio Gonz??lez
118     * @author Manuel de la Pe??a
119     * @author Levente Hud??k
120     * @author Kenneth Chang
121     */
122    public class EditFileEntryAction extends PortletAction {
123    
124            public static final String TEMP_RANDOM_SUFFIX = "--tempRandomSuffix--";
125    
126            @Override
127            public void processAction(
128                            ActionMapping actionMapping, ActionForm actionForm,
129                            PortletConfig portletConfig, ActionRequest actionRequest,
130                            ActionResponse actionResponse)
131                    throws Exception {
132    
133                    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
134    
135                    FileEntry fileEntry = null;
136    
137                    try {
138                            if (Validator.isNull(cmd)) {
139                                    UploadException uploadException =
140                                            (UploadException)actionRequest.getAttribute(
141                                                    WebKeys.UPLOAD_EXCEPTION);
142    
143                                    if (uploadException != null) {
144                                            if (uploadException.isExceededLiferayFileItemSizeLimit()) {
145                                                    throw new LiferayFileItemException();
146                                            }
147                                            else if (uploadException.isExceededSizeLimit()) {
148                                                    throw new FileSizeException(uploadException.getCause());
149                                            }
150    
151                                            throw new PortalException(uploadException.getCause());
152                                    }
153                            }
154                            else if (cmd.equals(Constants.ADD) ||
155                                             cmd.equals(Constants.ADD_DYNAMIC) ||
156                                             cmd.equals(Constants.UPDATE) ||
157                                             cmd.equals(Constants.UPDATE_AND_CHECKIN)) {
158    
159                                    fileEntry = updateFileEntry(
160                                            portletConfig, actionRequest, actionResponse);
161                            }
162                            else if (cmd.equals(Constants.ADD_MULTIPLE)) {
163                                    addMultipleFileEntries(
164                                            portletConfig, actionRequest, actionResponse);
165    
166                                    hideDefaultSuccessMessage(actionRequest);
167                            }
168                            else if (cmd.equals(Constants.ADD_TEMP)) {
169                                    addTempFileEntry(actionRequest, actionResponse);
170                            }
171                            else if (cmd.equals(Constants.DELETE)) {
172                                    deleteFileEntry(actionRequest, false);
173                            }
174                            else if (cmd.equals(Constants.DELETE_TEMP)) {
175                                    deleteTempFileEntry(actionRequest, actionResponse);
176                            }
177                            else if (cmd.equals(Constants.CANCEL_CHECKOUT)) {
178                                    cancelFileEntriesCheckOut(actionRequest);
179                            }
180                            else if (cmd.equals(Constants.CHECKIN)) {
181                                    checkInFileEntries(actionRequest);
182                            }
183                            else if (cmd.equals(Constants.CHECKOUT)) {
184                                    checkOutFileEntries(actionRequest);
185                            }
186                            else if (cmd.equals(Constants.MOVE)) {
187                                    moveFileEntries(actionRequest, false);
188                            }
189                            else if (cmd.equals(Constants.MOVE_FROM_TRASH)) {
190                                    moveFileEntries(actionRequest, true);
191                            }
192                            else if (cmd.equals(Constants.MOVE_TO_TRASH)) {
193                                    deleteFileEntry(actionRequest, true);
194                            }
195                            else if (cmd.equals(Constants.REVERT)) {
196                                    revertFileEntry(actionRequest);
197                            }
198    
199                            WindowState windowState = actionRequest.getWindowState();
200    
201                            if (cmd.equals(Constants.ADD_TEMP) ||
202                                    cmd.equals(Constants.DELETE_TEMP)) {
203    
204                                    setForward(actionRequest, ActionConstants.COMMON_NULL);
205                            }
206                            else if (cmd.equals(Constants.PREVIEW)) {
207                            }
208                            else if (!cmd.equals(Constants.MOVE_FROM_TRASH) &&
209                                             !windowState.equals(LiferayWindowState.POP_UP)) {
210    
211                                    sendRedirect(actionRequest, actionResponse);
212                            }
213                            else {
214                                    String redirect = ParamUtil.getString(
215                                            actionRequest, "redirect");
216                                    int workflowAction = ParamUtil.getInteger(
217                                            actionRequest, "workflowAction",
218                                            WorkflowConstants.ACTION_SAVE_DRAFT);
219    
220                                    if ((fileEntry != null) &&
221                                            (workflowAction == WorkflowConstants.ACTION_SAVE_DRAFT)) {
222    
223                                            redirect = getSaveAndContinueRedirect(
224                                                    portletConfig, actionRequest, fileEntry, redirect);
225    
226                                            sendRedirect(actionRequest, actionResponse, redirect);
227                                    }
228                                    else {
229                                            if (!windowState.equals(LiferayWindowState.POP_UP)) {
230                                                    sendRedirect(actionRequest, actionResponse);
231                                            }
232                                            else {
233                                                    redirect = PortalUtil.escapeRedirect(
234                                                            ParamUtil.getString(actionRequest, "redirect"));
235    
236                                                    if (Validator.isNotNull(redirect)) {
237                                                            if (cmd.equals(Constants.ADD) &&
238                                                                    (fileEntry != null)) {
239    
240                                                                    String portletId = HttpUtil.getParameter(
241                                                                            redirect, "p_p_id", false);
242    
243                                                                    String namespace =
244                                                                            PortalUtil.getPortletNamespace(portletId);
245    
246                                                                    redirect = HttpUtil.addParameter(
247                                                                            redirect, namespace + "className",
248                                                                            DLFileEntry.class.getName());
249                                                                    redirect = HttpUtil.addParameter(
250                                                                            redirect, namespace + "classPK",
251                                                                            fileEntry.getFileEntryId());
252                                                            }
253    
254                                                            actionResponse.sendRedirect(redirect);
255                                                    }
256                                            }
257                                    }
258                            }
259                    }
260                    catch (Exception e) {
261                            handleUploadException(
262                                    portletConfig, actionRequest, actionResponse, cmd, e);
263                    }
264            }
265    
266            @Override
267            public ActionForward render(
268                            ActionMapping actionMapping, ActionForm actionForm,
269                            PortletConfig portletConfig, RenderRequest renderRequest,
270                            RenderResponse renderResponse)
271                    throws Exception {
272    
273                    try {
274                            ActionUtil.getFileEntry(renderRequest);
275                    }
276                    catch (Exception e) {
277                            if (e instanceof NoSuchFileEntryException ||
278                                    e instanceof NoSuchFileVersionException ||
279                                    e instanceof NoSuchRepositoryEntryException ||
280                                    e instanceof PrincipalException) {
281    
282                                    SessionErrors.add(renderRequest, e.getClass());
283    
284                                    return actionMapping.findForward(
285                                            "portlet.document_library.error");
286                            }
287                            else {
288                                    throw e;
289                            }
290                    }
291    
292                    String forward = "portlet.document_library.edit_file_entry";
293    
294                    return actionMapping.findForward(getForward(renderRequest, forward));
295            }
296    
297            @Override
298            public void serveResource(
299                            ActionMapping actionMapping, ActionForm actionForm,
300                            PortletConfig portletConfig, ResourceRequest resourceRequest,
301                            ResourceResponse resourceResponse)
302                    throws Exception {
303    
304                    PortletContext portletContext = portletConfig.getPortletContext();
305    
306                    PortletRequestDispatcher portletRequestDispatcher =
307                            portletContext.getRequestDispatcher(
308                                    "/html/portlet/document_library/" +
309                                            "upload_multiple_file_entries_resources.jsp");
310    
311                    portletRequestDispatcher.include(resourceRequest, resourceResponse);
312            }
313    
314            protected void addMultipleFileEntries(
315                            PortletConfig portletConfig, ActionRequest actionRequest,
316                            ActionResponse actionResponse)
317                    throws Exception {
318    
319                    List<KeyValuePair> validFileNameKVPs = new ArrayList<KeyValuePair>();
320                    List<KeyValuePair> invalidFileNameKVPs = new ArrayList<KeyValuePair>();
321    
322                    String[] selectedFileNames = ParamUtil.getParameterValues(
323                            actionRequest, "selectedFileName", new String[0], false);
324    
325                    for (String selectedFileName : selectedFileNames) {
326                            addMultipleFileEntries(
327                                    portletConfig, actionRequest, actionResponse, selectedFileName,
328                                    validFileNameKVPs, invalidFileNameKVPs);
329                    }
330    
331                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
332    
333                    for (KeyValuePair validFileNameKVP : validFileNameKVPs) {
334                            String fileName = validFileNameKVP.getKey();
335                            String originalFileName = validFileNameKVP.getValue();
336    
337                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
338    
339                            jsonObject.put("added", Boolean.TRUE);
340                            jsonObject.put("fileName", fileName);
341                            jsonObject.put("originalFileName", originalFileName);
342    
343                            jsonArray.put(jsonObject);
344                    }
345    
346                    for (KeyValuePair invalidFileNameKVP : invalidFileNameKVPs) {
347                            String fileName = invalidFileNameKVP.getKey();
348                            String errorMessage = invalidFileNameKVP.getValue();
349    
350                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
351    
352                            jsonObject.put("added", Boolean.FALSE);
353                            jsonObject.put("errorMessage", errorMessage);
354                            jsonObject.put("fileName", fileName);
355                            jsonObject.put("originalFileName", fileName);
356    
357                            jsonArray.put(jsonObject);
358                    }
359    
360                    writeJSON(actionRequest, actionResponse, jsonArray);
361            }
362    
363            protected void addMultipleFileEntries(
364                            PortletConfig portletConfig, ActionRequest actionRequest,
365                            ActionResponse actionResponse, String selectedFileName,
366                            List<KeyValuePair> validFileNameKVPs,
367                            List<KeyValuePair> invalidFileNameKVPs)
368                    throws Exception {
369    
370                    String originalSelectedFileName = selectedFileName;
371    
372                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
373                            WebKeys.THEME_DISPLAY);
374    
375                    long repositoryId = ParamUtil.getLong(actionRequest, "repositoryId");
376                    long folderId = ParamUtil.getLong(actionRequest, "folderId");
377                    String description = ParamUtil.getString(actionRequest, "description");
378                    String changeLog = ParamUtil.getString(actionRequest, "changeLog");
379    
380                    FileEntry tempFileEntry = null;
381    
382                    try {
383                            tempFileEntry = TempFileUtil.getTempFile(
384                                    themeDisplay.getScopeGroupId(), themeDisplay.getUserId(),
385                                    selectedFileName, _TEMP_FOLDER_NAME);
386    
387                            String mimeType = tempFileEntry.getMimeType();
388    
389                            String extension = FileUtil.getExtension(selectedFileName);
390    
391                            int pos = selectedFileName.lastIndexOf(TEMP_RANDOM_SUFFIX);
392    
393                            if (pos != -1) {
394                                    selectedFileName = selectedFileName.substring(0, pos);
395    
396                                    if (Validator.isNotNull(extension)) {
397                                            selectedFileName =
398                                                    selectedFileName + StringPool.PERIOD + extension;
399                                    }
400                            }
401    
402                            while (true) {
403                                    try {
404                                            DLAppLocalServiceUtil.getFileEntry(
405                                                    themeDisplay.getScopeGroupId(), folderId,
406                                                    selectedFileName);
407    
408                                            StringBundler sb = new StringBundler(5);
409    
410                                            sb.append(FileUtil.stripExtension(selectedFileName));
411                                            sb.append(StringPool.DASH);
412                                            sb.append(StringUtil.randomString());
413    
414                                            if (Validator.isNotNull(extension)) {
415                                                    sb.append(StringPool.PERIOD);
416                                                    sb.append(extension);
417                                            }
418    
419                                            selectedFileName = sb.toString();
420                                    }
421                                    catch (Exception e) {
422                                            break;
423                                    }
424                            }
425    
426                            InputStream inputStream = tempFileEntry.getContentStream();
427                            long size = tempFileEntry.getSize();
428    
429                            ServiceContext serviceContext = ServiceContextFactory.getInstance(
430                                    DLFileEntry.class.getName(), actionRequest);
431    
432                            FileEntry fileEntry = DLAppServiceUtil.addFileEntry(
433                                    repositoryId, folderId, selectedFileName, mimeType,
434                                    selectedFileName, description, changeLog, inputStream, size,
435                                    serviceContext);
436    
437                            AssetPublisherUtil.addAndStoreSelection(
438                                    actionRequest, DLFileEntry.class.getName(),
439                                    fileEntry.getFileEntryId(), -1);
440    
441                            AssetPublisherUtil.addRecentFolderId(
442                                    actionRequest, DLFileEntry.class.getName(), folderId);
443    
444                            validFileNameKVPs.add(
445                                    new KeyValuePair(selectedFileName, originalSelectedFileName));
446    
447                            return;
448                    }
449                    catch (Exception e) {
450                            String errorMessage = getAddMultipleFileEntriesErrorMessage(
451                                    portletConfig, actionRequest, actionResponse, e);
452    
453                            invalidFileNameKVPs.add(
454                                    new KeyValuePair(originalSelectedFileName, errorMessage));
455                    }
456                    finally {
457                            if (tempFileEntry != null) {
458                                    TempFileUtil.deleteTempFile(tempFileEntry.getFileEntryId());
459                            }
460                    }
461            }
462    
463            protected void addTempFileEntry(
464                            ActionRequest actionRequest, ActionResponse actionResponse)
465                    throws Exception {
466    
467                    UploadPortletRequest uploadPortletRequest =
468                            PortalUtil.getUploadPortletRequest(actionRequest);
469    
470                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
471                            WebKeys.THEME_DISPLAY);
472    
473                    long folderId = ParamUtil.getLong(uploadPortletRequest, "folderId");
474                    String sourceFileName = uploadPortletRequest.getFileName("file");
475    
476                    String title = sourceFileName;
477    
478                    StringBundler sb = new StringBundler(5);
479    
480                    sb.append(FileUtil.stripExtension(sourceFileName));
481                    sb.append(TEMP_RANDOM_SUFFIX);
482                    sb.append(StringUtil.randomString());
483    
484                    String extension = FileUtil.getExtension(sourceFileName);
485    
486                    if (Validator.isNotNull(extension)) {
487                            sb.append(StringPool.PERIOD);
488                            sb.append(extension);
489                    }
490    
491                    sourceFileName = sb.toString();
492    
493                    InputStream inputStream = null;
494    
495                    try {
496                            inputStream = uploadPortletRequest.getFileAsStream("file");
497    
498                            String contentType = uploadPortletRequest.getContentType("file");
499    
500                            DLAppServiceUtil.addTempFileEntry(
501                                    themeDisplay.getScopeGroupId(), folderId, sourceFileName,
502                                    _TEMP_FOLDER_NAME, inputStream, contentType);
503    
504                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
505    
506                            jsonObject.put("name", sourceFileName);
507                            jsonObject.put("title", title);
508    
509                            writeJSON(actionRequest, actionResponse, jsonObject);
510                    }
511                    catch (Exception e) {
512                            UploadException uploadException =
513                                    (UploadException)actionRequest.getAttribute(
514                                            WebKeys.UPLOAD_EXCEPTION);
515    
516                            if ((uploadException != null) &&
517                                    (uploadException.getCause() instanceof IOFileUploadException)) {
518    
519                                    // Cancelled a temporary upload
520    
521                            }
522                            else if ((uploadException != null) &&
523                                             uploadException.isExceededSizeLimit()) {
524    
525                                    throw new FileSizeException(uploadException.getCause());
526                            }
527                            else {
528                                    throw e;
529                            }
530                    }
531                    finally {
532                            StreamUtil.cleanUp(inputStream);
533                    }
534            }
535    
536            protected void cancelFileEntriesCheckOut(ActionRequest actionRequest)
537                    throws Exception {
538    
539                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
540    
541                    if (fileEntryId > 0) {
542                            DLAppServiceUtil.cancelCheckOut(fileEntryId);
543                    }
544                    else {
545                            long[] fileEntryIds = StringUtil.split(
546                                    ParamUtil.getString(actionRequest, "fileEntryIds"), 0L);
547    
548                            for (int i = 0; i < fileEntryIds.length; i++) {
549                                    DLAppServiceUtil.cancelCheckOut(fileEntryIds[i]);
550                            }
551                    }
552            }
553    
554            protected void checkInFileEntries(ActionRequest actionRequest)
555                    throws Exception {
556    
557                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
558    
559                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
560                            actionRequest);
561    
562                    if (fileEntryId > 0) {
563                            DLAppServiceUtil.checkInFileEntry(
564                                    fileEntryId, false, StringPool.BLANK, serviceContext);
565                    }
566                    else {
567                            long[] fileEntryIds = StringUtil.split(
568                                    ParamUtil.getString(actionRequest, "fileEntryIds"), 0L);
569    
570                            for (int i = 0; i < fileEntryIds.length; i++) {
571                                    DLAppServiceUtil.checkInFileEntry(
572                                            fileEntryIds[i], false, StringPool.BLANK, serviceContext);
573                            }
574                    }
575            }
576    
577            protected void checkOutFileEntries(ActionRequest actionRequest)
578                    throws Exception {
579    
580                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
581    
582                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
583                            actionRequest);
584    
585                    if (fileEntryId > 0) {
586                            DLAppServiceUtil.checkOutFileEntry(fileEntryId, serviceContext);
587                    }
588                    else {
589                            long[] fileEntryIds = StringUtil.split(
590                                    ParamUtil.getString(actionRequest, "fileEntryIds"), 0L);
591    
592                            for (int i = 0; i < fileEntryIds.length; i++) {
593                                    DLAppServiceUtil.checkOutFileEntry(
594                                            fileEntryIds[i], serviceContext);
595                            }
596                    }
597            }
598    
599            protected void deleteFileEntry(
600                            ActionRequest actionRequest, boolean moveToTrash)
601                    throws Exception {
602    
603                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
604    
605                    if (fileEntryId == 0) {
606                            return;
607                    }
608    
609                    String version = ParamUtil.getString(actionRequest, "version");
610    
611                    if (Validator.isNotNull(version)) {
612                            DLAppServiceUtil.deleteFileVersion(fileEntryId, version);
613    
614                            return;
615                    }
616    
617                    if (!moveToTrash) {
618                            DLAppServiceUtil.deleteFileEntry(fileEntryId);
619    
620                            return;
621                    }
622    
623                    FileEntry fileEntry = DLAppServiceUtil.moveFileEntryToTrash(
624                            fileEntryId);
625    
626                    Map<String, String[]> data = new HashMap<String, String[]>();
627    
628                    data.put(
629                            "deleteEntryClassName", new String[] {DLFileEntry.class.getName()});
630    
631                    if (fileEntry != null) {
632                            data.put(
633                                    "deleteEntryTitle",
634                                    new String[] {
635                                            TrashUtil.getOriginalTitle(fileEntry.getTitle())});
636                    }
637    
638                    data.put(
639                            "restoreFileEntryIds", new String[] {String.valueOf(fileEntryId)});
640    
641                    SessionMessages.add(
642                            actionRequest,
643                            PortalUtil.getPortletId(actionRequest) +
644                                    SessionMessages.KEY_SUFFIX_DELETE_SUCCESS_DATA,
645                            data);
646    
647                    hideDefaultSuccessMessage(actionRequest);
648            }
649    
650            protected void deleteTempFileEntry(
651                            ActionRequest actionRequest, ActionResponse actionResponse)
652                    throws Exception {
653    
654                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
655                            WebKeys.THEME_DISPLAY);
656    
657                    long folderId = ParamUtil.getLong(actionRequest, "folderId");
658                    String fileName = ParamUtil.getString(actionRequest, "fileName");
659    
660                    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
661    
662                    try {
663                            DLAppServiceUtil.deleteTempFileEntry(
664                                    themeDisplay.getScopeGroupId(), folderId, fileName,
665                                    _TEMP_FOLDER_NAME);
666    
667                            jsonObject.put("deleted", Boolean.TRUE);
668                    }
669                    catch (Exception e) {
670                            String errorMessage = themeDisplay.translate(
671                                    "an-unexpected-error-occurred-while-deleting-the-file");
672    
673                            jsonObject.put("deleted", Boolean.FALSE);
674                            jsonObject.put("errorMessage", errorMessage);
675                    }
676    
677                    writeJSON(actionRequest, actionResponse, jsonObject);
678            }
679    
680            protected String getAddMultipleFileEntriesErrorMessage(
681                            PortletConfig portletConfig, ActionRequest actionRequest,
682                            ActionResponse actionResponse, Exception e)
683                    throws Exception {
684    
685                    String errorMessage = null;
686    
687                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
688                            WebKeys.THEME_DISPLAY);
689    
690                    if (e instanceof AntivirusScannerException) {
691                            AntivirusScannerException ase = (AntivirusScannerException)e;
692    
693                            errorMessage = themeDisplay.translate(ase.getMessageKey());
694                    }
695                    else if (e instanceof AssetCategoryException) {
696                            AssetCategoryException ace = (AssetCategoryException)e;
697    
698                            AssetVocabulary assetVocabulary = ace.getVocabulary();
699    
700                            String vocabularyTitle = StringPool.BLANK;
701    
702                            if (assetVocabulary != null) {
703                                    vocabularyTitle = assetVocabulary.getTitle(
704                                            themeDisplay.getLocale());
705                            }
706    
707                            if (ace.getType() == AssetCategoryException.AT_LEAST_ONE_CATEGORY) {
708                                    errorMessage = themeDisplay.translate(
709                                            "please-select-at-least-one-category-for-x",
710                                            vocabularyTitle);
711                            }
712                            else if (ace.getType() ==
713                                                    AssetCategoryException.TOO_MANY_CATEGORIES) {
714    
715                                    errorMessage = themeDisplay.translate(
716                                            "you-cannot-select-more-than-one-category-for-x",
717                                            vocabularyTitle);
718                            }
719                    }
720                    else if (e instanceof DuplicateFileException) {
721                            errorMessage = themeDisplay.translate(
722                                    "the-folder-you-selected-already-has-an-entry-with-this-name." +
723                                            "-please-select-a-different-folder");
724                    }
725                    else if (e instanceof FileExtensionException) {
726                            errorMessage = themeDisplay.translate(
727                                    "please-enter-a-file-with-a-valid-extension-x",
728                                            StringUtil.merge(
729                                                    getAllowedFileExtensions(
730                                                            portletConfig, actionRequest, actionResponse)));
731                    }
732                    else if (e instanceof FileNameException) {
733                            errorMessage = themeDisplay.translate(
734                                    "please-enter-a-file-with-a-valid-file-name");
735                    }
736                    else if (e instanceof FileSizeException) {
737                            long maxSizeMB = PrefsPropsUtil.getLong(
738                                    PropsKeys.DL_FILE_MAX_SIZE) / 1024 / 1024;
739    
740                            errorMessage = themeDisplay.translate(
741                                    "file-size-is-larger-than-x-megabytes", maxSizeMB);
742                    }
743                    else if (e instanceof InvalidFileEntryTypeException) {
744                            errorMessage = themeDisplay.translate(
745                                    "the-document-type-you-selected-is-not-valid-for-this-folder");
746                    }
747                    else {
748                            errorMessage = themeDisplay.translate(
749                                    "an-unexpected-error-occurred-while-saving-your-document");
750                    }
751    
752                    return errorMessage;
753            }
754    
755            protected String[] getAllowedFileExtensions(
756                            PortletConfig portletConfig, PortletRequest portletRequest,
757                            PortletResponse portletResponse)
758                    throws PortalException, SystemException {
759    
760                    String portletName = portletConfig.getPortletName();
761    
762                    if (!portletName.equals(PortletKeys.MEDIA_GALLERY_DISPLAY)) {
763                            return PrefsPropsUtil.getStringArray(
764                                    PropsKeys.DL_FILE_EXTENSIONS, StringPool.COMMA);
765                    }
766                    else {
767                            PortletPreferences portletPreferences = getStrictPortletSetup(
768                                    portletRequest);
769    
770                            if (portletPreferences == null) {
771                                    portletPreferences = portletRequest.getPreferences();
772                            }
773    
774                            Set<String> extensions = new HashSet<String>();
775    
776                            String[] mimeTypes = DLUtil.getMediaGalleryMimeTypes(
777                                    portletPreferences, portletRequest);
778    
779                            for (String mimeType : mimeTypes) {
780                                    extensions.addAll(MimeTypesUtil.getExtensions(mimeType));
781                            }
782    
783                            return extensions.toArray(new String[extensions.size()]);
784                    }
785            }
786    
787            protected String getSaveAndContinueRedirect(
788                            PortletConfig portletConfig, ActionRequest actionRequest,
789                            FileEntry fileEntry, String redirect)
790                    throws Exception {
791    
792                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
793                            WebKeys.THEME_DISPLAY);
794    
795                    PortletURLImpl portletURL = new PortletURLImpl(
796                            actionRequest, portletConfig.getPortletName(),
797                            themeDisplay.getPlid(), PortletRequest.RENDER_PHASE);
798    
799                    portletURL.setParameter(
800                            "struts_action", "/document_library/edit_file_entry");
801                    portletURL.setParameter(Constants.CMD, Constants.UPDATE, false);
802                    portletURL.setParameter("redirect", redirect, false);
803    
804                    String referringPortletResource = ParamUtil.getString(
805                            actionRequest, "referringPortletResource");
806    
807                    portletURL.setParameter(
808                            "referringPortletResource", referringPortletResource, false);
809    
810                    portletURL.setParameter(
811                            "groupId", String.valueOf(fileEntry.getGroupId()), false);
812                    portletURL.setParameter(
813                            "fileEntryId", String.valueOf(fileEntry.getFileEntryId()), false);
814                    portletURL.setParameter(
815                            "version", String.valueOf(fileEntry.getVersion()), false);
816                    portletURL.setWindowState(actionRequest.getWindowState());
817    
818                    return portletURL.toString();
819            }
820    
821            protected void handleUploadException(
822                            PortletConfig portletConfig, ActionRequest actionRequest,
823                            ActionResponse actionResponse, String cmd, Exception e)
824                    throws Exception {
825    
826                    if (e instanceof AssetCategoryException ||
827                            e instanceof AssetTagException) {
828    
829                            SessionErrors.add(actionRequest, e.getClass(), e);
830                    }
831                    else if (e instanceof AntivirusScannerException ||
832                                     e instanceof DuplicateFileException ||
833                                     e instanceof DuplicateFolderNameException ||
834                                     e instanceof LiferayFileItemException ||
835                                     e instanceof FileExtensionException ||
836                                     e instanceof FileMimeTypeException ||
837                                     e instanceof FileNameException ||
838                                     e instanceof FileSizeException ||
839                                     e instanceof NoSuchFolderException ||
840                                     e instanceof SourceFileNameException ||
841                                     e instanceof StorageFieldRequiredException) {
842    
843                            if (Validator.isNull(cmd)) {
844                                    UploadException uploadException =
845                                            (UploadException)actionRequest.getAttribute(
846                                                    WebKeys.UPLOAD_EXCEPTION);
847    
848                                    if (uploadException != null) {
849                                            String uploadExceptionRedirect = ParamUtil.getString(
850                                                    actionRequest, "uploadExceptionRedirect");
851    
852                                            actionResponse.sendRedirect(uploadExceptionRedirect);
853                                    }
854    
855                                    SessionErrors.add(actionRequest, e.getClass());
856    
857                                    return;
858                            }
859                            else if (!cmd.equals(Constants.ADD_DYNAMIC) &&
860                                             !cmd.equals(Constants.ADD_MULTIPLE) &&
861                                             !cmd.equals(Constants.ADD_TEMP)) {
862    
863                                    if (e instanceof AntivirusScannerException) {
864                                            SessionErrors.add(actionRequest, e.getClass(), e);
865                                    }
866                                    else {
867                                            SessionErrors.add(actionRequest, e.getClass());
868                                    }
869    
870                                    return;
871                            }
872    
873                            if (e instanceof AntivirusScannerException ||
874                                    e instanceof DuplicateFileException ||
875                                    e instanceof FileExtensionException ||
876                                    e instanceof FileNameException ||
877                                    e instanceof FileSizeException) {
878    
879                                    HttpServletResponse response =
880                                            PortalUtil.getHttpServletResponse(actionResponse);
881    
882                                    response.setContentType(ContentTypes.TEXT_HTML);
883                                    response.setStatus(HttpServletResponse.SC_OK);
884    
885                                    String errorMessage = StringPool.BLANK;
886                                    int errorType = 0;
887    
888                                    ThemeDisplay themeDisplay =
889                                            (ThemeDisplay)actionRequest.getAttribute(
890                                                    WebKeys.THEME_DISPLAY);
891    
892                                    if (e instanceof AntivirusScannerException) {
893                                            AntivirusScannerException ase =
894                                                    (AntivirusScannerException)e;
895    
896                                            errorMessage = themeDisplay.translate(ase.getMessageKey());
897                                            errorType =
898                                                    ServletResponseConstants.SC_FILE_ANTIVIRUS_EXCEPTION;
899                                    }
900    
901                                    if (e instanceof DuplicateFileException) {
902                                            errorMessage = themeDisplay.translate(
903                                                    "please-enter-a-unique-document-name");
904                                            errorType =
905                                                    ServletResponseConstants.SC_DUPLICATE_FILE_EXCEPTION;
906                                    }
907                                    else if (e instanceof FileExtensionException) {
908                                            errorMessage = themeDisplay.translate(
909                                                    "please-enter-a-file-with-a-valid-extension-x",
910                                                    StringUtil.merge(
911                                                            getAllowedFileExtensions(
912                                                                    portletConfig, actionRequest, actionResponse)));
913                                            errorType =
914                                                    ServletResponseConstants.SC_FILE_EXTENSION_EXCEPTION;
915                                    }
916                                    else if (e instanceof FileNameException) {
917                                            errorMessage = themeDisplay.translate(
918                                                    "please-enter-a-file-with-a-valid-file-name");
919                                            errorType = ServletResponseConstants.SC_FILE_NAME_EXCEPTION;
920                                    }
921                                    else if (e instanceof FileSizeException) {
922                                            long fileMaxSize = PrefsPropsUtil.getLong(
923                                                    PropsKeys.DL_FILE_MAX_SIZE);
924    
925                                            if (fileMaxSize == 0) {
926                                                    fileMaxSize = PrefsPropsUtil.getLong(
927                                                            PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE);
928                                            }
929    
930                                            fileMaxSize /= 1024;
931    
932                                            errorMessage = themeDisplay.translate(
933                                                    "please-enter-a-file-with-a-valid-file-size-no-larger" +
934                                                            "-than-x",
935                                                    fileMaxSize);
936    
937                                            errorType = ServletResponseConstants.SC_FILE_SIZE_EXCEPTION;
938                                    }
939    
940                                    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
941    
942                                    jsonObject.put("message", errorMessage);
943                                    jsonObject.put("status", errorType);
944    
945                                    writeJSON(actionRequest, actionResponse, jsonObject);
946                            }
947    
948                            if (e instanceof AntivirusScannerException) {
949                                    SessionErrors.add(actionRequest, e.getClass(), e);
950                            }
951                            else {
952                                    SessionErrors.add(actionRequest, e.getClass());
953                            }
954                    }
955                    else if (e instanceof DuplicateLockException ||
956                                     e instanceof InvalidFileVersionException ||
957                                     e instanceof NoSuchFileEntryException ||
958                                     e instanceof PrincipalException) {
959    
960                            if (e instanceof DuplicateLockException) {
961                                    DuplicateLockException dle = (DuplicateLockException)e;
962    
963                                    SessionErrors.add(actionRequest, dle.getClass(), dle.getLock());
964                            }
965                            else {
966                                    SessionErrors.add(actionRequest, e.getClass());
967                            }
968    
969                            setForward(actionRequest, "portlet.document_library.error");
970                    }
971                    else {
972                            throw e;
973                    }
974            }
975    
976            protected void moveFileEntries(
977                            ActionRequest actionRequest, boolean moveFromTrash)
978                    throws Exception {
979    
980                    long[] fileEntryIds = null;
981    
982                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
983    
984                    if (fileEntryId > 0) {
985                            fileEntryIds = new long[] {fileEntryId};
986                    }
987                    else {
988                            fileEntryIds = StringUtil.split(
989                                    ParamUtil.getString(actionRequest, "fileEntryIds"), 0L);
990                    }
991    
992                    long newFolderId = ParamUtil.getLong(actionRequest, "newFolderId");
993    
994                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
995                            DLFileEntry.class.getName(), actionRequest);
996    
997                    for (long moveFileEntryId : fileEntryIds) {
998                            if (moveFromTrash) {
999                                    DLAppServiceUtil.moveFileEntryFromTrash(
1000                                            moveFileEntryId, newFolderId, serviceContext);
1001                            }
1002    
1003                            else {
1004                                    DLAppServiceUtil.moveFileEntry(
1005                                            moveFileEntryId, newFolderId, serviceContext);
1006                            }
1007                    }
1008            }
1009    
1010            protected void revertFileEntry(ActionRequest actionRequest)
1011                    throws Exception {
1012    
1013                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
1014                    String version = ParamUtil.getString(actionRequest, "version");
1015    
1016                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
1017                            DLFileEntry.class.getName(), actionRequest);
1018    
1019                    DLAppServiceUtil.revertFileEntry(fileEntryId, version, serviceContext);
1020            }
1021    
1022            protected FileEntry updateFileEntry(
1023                            PortletConfig portletConfig, ActionRequest actionRequest,
1024                            ActionResponse actionResponse)
1025                    throws Exception {
1026    
1027                    UploadPortletRequest uploadPortletRequest =
1028                            PortalUtil.getUploadPortletRequest(actionRequest);
1029    
1030                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
1031                            WebKeys.THEME_DISPLAY);
1032    
1033                    String cmd = ParamUtil.getString(uploadPortletRequest, Constants.CMD);
1034    
1035                    long fileEntryId = ParamUtil.getLong(
1036                            uploadPortletRequest, "fileEntryId");
1037    
1038                    long repositoryId = ParamUtil.getLong(
1039                            uploadPortletRequest, "repositoryId");
1040                    long folderId = ParamUtil.getLong(uploadPortletRequest, "folderId");
1041                    String sourceFileName = uploadPortletRequest.getFileName("file");
1042                    String title = ParamUtil.getString(uploadPortletRequest, "title");
1043                    String description = ParamUtil.getString(
1044                            uploadPortletRequest, "description");
1045                    String changeLog = ParamUtil.getString(
1046                            uploadPortletRequest, "changeLog");
1047                    boolean majorVersion = ParamUtil.getBoolean(
1048                            uploadPortletRequest, "majorVersion");
1049    
1050                    if (folderId > 0) {
1051                            Folder folder = DLAppServiceUtil.getFolder(folderId);
1052    
1053                            if (folder.getGroupId() != themeDisplay.getScopeGroupId()) {
1054                                    throw new NoSuchFolderException("{folderId=" + folderId + "}");
1055                            }
1056                    }
1057    
1058                    InputStream inputStream = null;
1059    
1060                    try {
1061                            String contentType = uploadPortletRequest.getContentType("file");
1062    
1063                            long size = uploadPortletRequest.getSize("file");
1064    
1065                            if ((cmd.equals(Constants.ADD) ||
1066                                     cmd.equals(Constants.ADD_DYNAMIC)) &&
1067                                    (size == 0)) {
1068    
1069                                    contentType = MimeTypesUtil.getContentType(title);
1070                            }
1071    
1072                            if (cmd.equals(Constants.ADD) ||
1073                                    cmd.equals(Constants.ADD_DYNAMIC) || (size > 0)) {
1074    
1075                                    String portletName = portletConfig.getPortletName();
1076    
1077                                    if (portletName.equals(PortletKeys.MEDIA_GALLERY_DISPLAY)) {
1078                                            PortletPreferences portletPreferences =
1079                                                    getStrictPortletSetup(actionRequest);
1080    
1081                                            if (portletPreferences == null) {
1082                                                    portletPreferences = actionRequest.getPreferences();
1083                                            }
1084    
1085                                            String[] mimeTypes = DLUtil.getMediaGalleryMimeTypes(
1086                                                    portletPreferences, actionRequest);
1087    
1088                                            if (Arrays.binarySearch(mimeTypes, contentType) < 0) {
1089                                                    throw new FileMimeTypeException(contentType);
1090                                            }
1091                                    }
1092                            }
1093    
1094                            inputStream = uploadPortletRequest.getFileAsStream("file");
1095    
1096                            ServiceContext serviceContext = ServiceContextFactory.getInstance(
1097                                    DLFileEntry.class.getName(), uploadPortletRequest);
1098    
1099                            FileEntry fileEntry = null;
1100    
1101                            if (cmd.equals(Constants.ADD) ||
1102                                    cmd.equals(Constants.ADD_DYNAMIC)) {
1103    
1104                                    // Add file entry
1105    
1106                                    fileEntry = DLAppServiceUtil.addFileEntry(
1107                                            repositoryId, folderId, sourceFileName, contentType, title,
1108                                            description, changeLog, inputStream, size, serviceContext);
1109    
1110                                    AssetPublisherUtil.addAndStoreSelection(
1111                                            actionRequest, DLFileEntry.class.getName(),
1112                                            fileEntry.getFileEntryId(), -1);
1113    
1114                                    if (cmd.equals(Constants.ADD_DYNAMIC)) {
1115                                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
1116    
1117                                            jsonObject.put("fileEntryId", fileEntry.getFileEntryId());
1118    
1119                                            writeJSON(actionRequest, actionResponse, jsonObject);
1120                                    }
1121                            }
1122                            else if (cmd.equals(Constants.UPDATE_AND_CHECKIN)) {
1123    
1124                                    // Update file entry and checkin
1125    
1126                                    fileEntry = DLAppServiceUtil.updateFileEntryAndCheckIn(
1127                                            fileEntryId, sourceFileName, contentType, title,
1128                                            description, changeLog, majorVersion, inputStream, size,
1129                                            serviceContext);
1130                            }
1131                            else {
1132    
1133                                    // Update file entry
1134    
1135                                    fileEntry = DLAppServiceUtil.updateFileEntry(
1136                                            fileEntryId, sourceFileName, contentType, title,
1137                                            description, changeLog, majorVersion, inputStream, size,
1138                                            serviceContext);
1139                            }
1140    
1141                            AssetPublisherUtil.addRecentFolderId(
1142                                    actionRequest, DLFileEntry.class.getName(), folderId);
1143    
1144                            return fileEntry;
1145                    }
1146                    catch (Exception e) {
1147                            UploadException uploadException =
1148                                    (UploadException)actionRequest.getAttribute(
1149                                            WebKeys.UPLOAD_EXCEPTION);
1150    
1151                            if (uploadException != null) {
1152                                    if (uploadException.isExceededLiferayFileItemSizeLimit()) {
1153                                            throw new LiferayFileItemException();
1154                                    }
1155                                    else if (uploadException.isExceededSizeLimit()) {
1156                                            throw new FileSizeException(uploadException.getCause());
1157                                    }
1158                            }
1159    
1160                            throw e;
1161                    }
1162                    finally {
1163                            StreamUtil.cleanUp(inputStream);
1164                    }
1165            }
1166    
1167            private static final String _TEMP_FOLDER_NAME =
1168                    EditFileEntryAction.class.getName();
1169    
1170    }