001    /**
002     * Copyright (c) 2000-2012 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.json.JSONArray;
021    import com.liferay.portal.kernel.json.JSONFactoryUtil;
022    import com.liferay.portal.kernel.json.JSONObject;
023    import com.liferay.portal.kernel.language.LanguageUtil;
024    import com.liferay.portal.kernel.portlet.LiferayPortletConfig;
025    import com.liferay.portal.kernel.portlet.LiferayWindowState;
026    import com.liferay.portal.kernel.repository.model.FileEntry;
027    import com.liferay.portal.kernel.repository.model.Folder;
028    import com.liferay.portal.kernel.servlet.ServletResponseConstants;
029    import com.liferay.portal.kernel.servlet.ServletResponseUtil;
030    import com.liferay.portal.kernel.servlet.SessionErrors;
031    import com.liferay.portal.kernel.servlet.SessionMessages;
032    import com.liferay.portal.kernel.upload.UploadException;
033    import com.liferay.portal.kernel.upload.UploadPortletRequest;
034    import com.liferay.portal.kernel.util.Constants;
035    import com.liferay.portal.kernel.util.ContentTypes;
036    import com.liferay.portal.kernel.util.KeyValuePair;
037    import com.liferay.portal.kernel.util.MimeTypesUtil;
038    import com.liferay.portal.kernel.util.ParamUtil;
039    import com.liferay.portal.kernel.util.PropsKeys;
040    import com.liferay.portal.kernel.util.StreamUtil;
041    import com.liferay.portal.kernel.util.StringPool;
042    import com.liferay.portal.kernel.util.StringUtil;
043    import com.liferay.portal.kernel.util.TempFileUtil;
044    import com.liferay.portal.kernel.util.Validator;
045    import com.liferay.portal.security.auth.PrincipalException;
046    import com.liferay.portal.service.ServiceContext;
047    import com.liferay.portal.service.ServiceContextFactory;
048    import com.liferay.portal.struts.ActionConstants;
049    import com.liferay.portal.struts.PortletAction;
050    import com.liferay.portal.theme.ThemeDisplay;
051    import com.liferay.portal.util.PortalUtil;
052    import com.liferay.portal.util.PortletKeys;
053    import com.liferay.portal.util.PrefsPropsUtil;
054    import com.liferay.portal.util.WebKeys;
055    import com.liferay.portlet.PortletPreferencesFactoryUtil;
056    import com.liferay.portlet.asset.AssetCategoryException;
057    import com.liferay.portlet.asset.AssetTagException;
058    import com.liferay.portlet.asset.model.AssetVocabulary;
059    import com.liferay.portlet.assetpublisher.util.AssetPublisherUtil;
060    import com.liferay.portlet.documentlibrary.DuplicateFileException;
061    import com.liferay.portlet.documentlibrary.DuplicateFolderNameException;
062    import com.liferay.portlet.documentlibrary.FileExtensionException;
063    import com.liferay.portlet.documentlibrary.FileMimeTypeException;
064    import com.liferay.portlet.documentlibrary.FileNameException;
065    import com.liferay.portlet.documentlibrary.FileSizeException;
066    import com.liferay.portlet.documentlibrary.InvalidFileEntryTypeException;
067    import com.liferay.portlet.documentlibrary.InvalidFileVersionException;
068    import com.liferay.portlet.documentlibrary.NoSuchFileEntryException;
069    import com.liferay.portlet.documentlibrary.NoSuchFileVersionException;
070    import com.liferay.portlet.documentlibrary.NoSuchFolderException;
071    import com.liferay.portlet.documentlibrary.SourceFileNameException;
072    import com.liferay.portlet.documentlibrary.model.DLFileEntry;
073    import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil;
074    import com.liferay.portlet.documentlibrary.util.DLUtil;
075    import com.liferay.portlet.dynamicdatamapping.StorageFieldRequiredException;
076    
077    import java.io.InputStream;
078    
079    import java.util.ArrayList;
080    import java.util.Arrays;
081    import java.util.HashMap;
082    import java.util.List;
083    import java.util.Map;
084    
085    import javax.portlet.ActionRequest;
086    import javax.portlet.ActionResponse;
087    import javax.portlet.PortletConfig;
088    import javax.portlet.PortletContext;
089    import javax.portlet.PortletPreferences;
090    import javax.portlet.PortletRequestDispatcher;
091    import javax.portlet.RenderRequest;
092    import javax.portlet.RenderResponse;
093    import javax.portlet.ResourceRequest;
094    import javax.portlet.ResourceResponse;
095    import javax.portlet.WindowState;
096    
097    import javax.servlet.http.HttpServletResponse;
098    
099    import org.apache.commons.fileupload.FileUploadBase.IOFileUploadException;
100    import org.apache.struts.action.ActionForm;
101    import org.apache.struts.action.ActionForward;
102    import org.apache.struts.action.ActionMapping;
103    
104    /**
105     * @author Brian Wing Shun Chan
106     * @author Alexander Chow
107     * @author Sergio González
108     * @author Manuel de la Peña
109     * @author Levente Hudák
110     */
111    public class EditFileEntryAction extends PortletAction {
112    
113            @Override
114            public void processAction(
115                            ActionMapping mapping, ActionForm form, PortletConfig portletConfig,
116                            ActionRequest actionRequest, ActionResponse actionResponse)
117                    throws Exception {
118    
119                    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
120    
121                    try {
122                            if (Validator.isNull(cmd)) {
123                                    UploadException uploadException =
124                                            (UploadException)actionRequest.getAttribute(
125                                                    WebKeys.UPLOAD_EXCEPTION);
126    
127                                    if (uploadException != null) {
128                                            if (uploadException.isExceededSizeLimit()) {
129                                                    throw new FileSizeException(uploadException.getCause());
130                                            }
131    
132                                            throw new PortalException(uploadException.getCause());
133                                    }
134                            }
135                            else if (cmd.equals(Constants.ADD) ||
136                                             cmd.equals(Constants.ADD_DYNAMIC) ||
137                                             cmd.equals(Constants.UPDATE) ||
138                                             cmd.equals(Constants.UPDATE_AND_CHECKIN)) {
139    
140                                    updateFileEntry(portletConfig, actionRequest, actionResponse);
141                            }
142                            else if (cmd.equals(Constants.ADD_MULTIPLE)) {
143                                    addMultipleFileEntries(actionRequest, actionResponse);
144                            }
145                            else if (cmd.equals(Constants.ADD_TEMP)) {
146                                    addTempFileEntry(actionRequest);
147                            }
148                            else if (cmd.equals(Constants.DELETE)) {
149                                    deleteFileEntry(
150                                            (LiferayPortletConfig)portletConfig, actionRequest, false);
151                            }
152                            else if (cmd.equals(Constants.DELETE_TEMP)) {
153                                    deleteTempFileEntry(actionRequest, actionResponse);
154                            }
155                            else if (cmd.equals(Constants.CANCEL_CHECKOUT)) {
156                                    cancelFileEntriesCheckOut(actionRequest);
157                            }
158                            else if (cmd.equals(Constants.CHECKIN)) {
159                                    checkInFileEntries(actionRequest);
160                            }
161                            else if (cmd.equals(Constants.CHECKOUT)) {
162                                    checkOutFileEntries(actionRequest);
163                            }
164                            else if (cmd.equals(Constants.MOVE)) {
165                                    moveFileEntries(actionRequest, false);
166                            }
167                            else if (cmd.equals(Constants.MOVE_FROM_TRASH)) {
168                                    moveFileEntries(actionRequest, true);
169                            }
170                            else if (cmd.equals(Constants.MOVE_TO_TRASH)) {
171                                    deleteFileEntry(
172                                            (LiferayPortletConfig)portletConfig, actionRequest, true);
173                            }
174                            else if (cmd.equals(Constants.REVERT)) {
175                                    revertFileEntry(actionRequest);
176                            }
177    
178                            WindowState windowState = actionRequest.getWindowState();
179    
180                            if (cmd.equals(Constants.ADD_TEMP) ||
181                                    cmd.equals(Constants.DELETE_TEMP)) {
182    
183                                    setForward(actionRequest, ActionConstants.COMMON_NULL);
184                            }
185                            else if (cmd.equals(Constants.PREVIEW)) {
186                            }
187                            else if (!cmd.equals(Constants.MOVE_FROM_TRASH) &&
188                                             !windowState.equals(LiferayWindowState.POP_UP)) {
189    
190                                    sendRedirect(actionRequest, actionResponse);
191                            }
192                            else {
193                                    String redirect = PortalUtil.escapeRedirect(
194                                            ParamUtil.getString(actionRequest, "redirect"));
195    
196                                    if (Validator.isNotNull(redirect)) {
197                                            actionResponse.sendRedirect(redirect);
198                                    }
199                            }
200                    }
201                    catch (Exception e) {
202                            handleUploadException(actionRequest, actionResponse, cmd, e);
203                    }
204            }
205    
206            @Override
207            public ActionForward render(
208                            ActionMapping mapping, ActionForm form, PortletConfig portletConfig,
209                            RenderRequest renderRequest, RenderResponse renderResponse)
210                    throws Exception {
211    
212                    try {
213                            ActionUtil.getFileEntry(renderRequest);
214                    }
215                    catch (Exception e) {
216                            if (e instanceof NoSuchFileEntryException ||
217                                    e instanceof NoSuchFileVersionException ||
218                                    e instanceof NoSuchRepositoryEntryException ||
219                                    e instanceof PrincipalException) {
220    
221                                    SessionErrors.add(renderRequest, e.getClass());
222    
223                                    return mapping.findForward("portlet.document_library.error");
224                            }
225                            else {
226                                    throw e;
227                            }
228                    }
229    
230                    String forward = "portlet.document_library.edit_file_entry";
231    
232                    return mapping.findForward(getForward(renderRequest, forward));
233            }
234    
235            @Override
236            public void serveResource(
237                            ActionMapping mapping, ActionForm form, PortletConfig portletConfig,
238                            ResourceRequest resourceRequest, ResourceResponse resourceResponse)
239                    throws Exception {
240    
241                    PortletContext portletContext = portletConfig.getPortletContext();
242    
243                    PortletRequestDispatcher portletRequestDispatcher =
244                            portletContext.getRequestDispatcher(
245                                    "/html/portlet/document_library/" +
246                                            "upload_multiple_file_entries_resources.jsp");
247    
248                    portletRequestDispatcher.include(resourceRequest, resourceResponse);
249            }
250    
251            protected void addMultipleFileEntries(
252                            ActionRequest actionRequest, ActionResponse actionResponse)
253                    throws Exception {
254    
255                    List<String> validFileNames = new ArrayList<String>();
256                    List<KeyValuePair> invalidFileNameKVPs = new ArrayList<KeyValuePair>();
257    
258                    String[] selectedFileNames = ParamUtil.getParameterValues(
259                            actionRequest, "selectedFileName");
260    
261                    for (String selectedFileName : selectedFileNames) {
262                            addMultipleFileEntries(
263                                    actionRequest, actionResponse, selectedFileName, validFileNames,
264                                    invalidFileNameKVPs);
265                    }
266    
267                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
268    
269                    for (String validFileName : validFileNames) {
270                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
271    
272                            jsonObject.put("added", Boolean.TRUE);
273                            jsonObject.put("fileName", validFileName);
274    
275                            jsonArray.put(jsonObject);
276                    }
277    
278                    for (KeyValuePair invalidFileNameKVP : invalidFileNameKVPs) {
279                            String fileName = invalidFileNameKVP.getKey();
280                            String errorMessage = invalidFileNameKVP.getValue();
281    
282                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
283    
284                            jsonObject.put("added", Boolean.FALSE);
285                            jsonObject.put("errorMessage", errorMessage);
286                            jsonObject.put("fileName", fileName);
287    
288                            jsonArray.put(jsonObject);
289                    }
290    
291                    writeJSON(actionRequest, actionResponse, jsonArray);
292            }
293    
294            protected void addMultipleFileEntries(
295                            ActionRequest actionRequest, ActionResponse actionResponse,
296                            String selectedFileName, List<String> validFileNames,
297                            List<KeyValuePair> invalidFileNameKVPs)
298                    throws Exception {
299    
300                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
301                            WebKeys.THEME_DISPLAY);
302    
303                    long repositoryId = ParamUtil.getLong(actionRequest, "repositoryId");
304                    long folderId = ParamUtil.getLong(actionRequest, "folderId");
305                    String description = ParamUtil.getString(actionRequest, "description");
306                    String changeLog = ParamUtil.getString(actionRequest, "changeLog");
307    
308                    FileEntry tempFileEntry = null;
309    
310                    try {
311                            tempFileEntry = TempFileUtil.getTempFile(
312                                    themeDisplay.getScopeGroupId(), themeDisplay.getUserId(),
313                                    selectedFileName, _TEMP_FOLDER_NAME);
314    
315                            String mimeType = tempFileEntry.getMimeType();
316                            InputStream inputStream = tempFileEntry.getContentStream();
317                            long size = tempFileEntry.getSize();
318    
319                            ServiceContext serviceContext = ServiceContextFactory.getInstance(
320                                    DLFileEntry.class.getName(), actionRequest);
321    
322                            FileEntry fileEntry = DLAppServiceUtil.addFileEntry(
323                                    repositoryId, folderId, selectedFileName, mimeType,
324                                    selectedFileName, description, changeLog, inputStream, size,
325                                    serviceContext);
326    
327                            AssetPublisherUtil.addAndStoreSelection(
328                                    actionRequest, DLFileEntry.class.getName(),
329                                    fileEntry.getFileEntryId(), -1);
330    
331                            AssetPublisherUtil.addRecentFolderId(
332                                    actionRequest, DLFileEntry.class.getName(), folderId);
333    
334                            validFileNames.add(selectedFileName);
335    
336                            return;
337                    }
338                    catch (Exception e) {
339                            String errorMessage = getAddMultipleFileEntriesErrorMessage(
340                                    themeDisplay, e);
341    
342                            invalidFileNameKVPs.add(
343                                    new KeyValuePair(selectedFileName, errorMessage));
344                    }
345                    finally {
346                            if (tempFileEntry != null) {
347                                    TempFileUtil.deleteTempFile(tempFileEntry.getFileEntryId());
348                            }
349                    }
350            }
351    
352            protected void addTempFileEntry(ActionRequest actionRequest)
353                    throws Exception {
354    
355                    UploadPortletRequest uploadPortletRequest =
356                            PortalUtil.getUploadPortletRequest(actionRequest);
357    
358                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
359                            WebKeys.THEME_DISPLAY);
360    
361                    long folderId = ParamUtil.getLong(uploadPortletRequest, "folderId");
362                    String sourceFileName = uploadPortletRequest.getFileName("file");
363    
364                    InputStream inputStream = null;
365    
366                    try {
367                            inputStream = uploadPortletRequest.getFileAsStream("file");
368    
369                            String contentType = uploadPortletRequest.getContentType("file");
370    
371                            DLAppServiceUtil.addTempFileEntry(
372                                    themeDisplay.getScopeGroupId(), folderId, sourceFileName,
373                                    _TEMP_FOLDER_NAME, inputStream, contentType);
374                    }
375                    catch (Exception e) {
376                            UploadException uploadException =
377                                    (UploadException)actionRequest.getAttribute(
378                                            WebKeys.UPLOAD_EXCEPTION);
379    
380                            if ((uploadException != null) &&
381                                    (uploadException.getCause() instanceof IOFileUploadException)) {
382    
383                                    // Cancelled a temporary upload
384    
385                            }
386                            else if ((uploadException != null) &&
387                                             uploadException.isExceededSizeLimit()) {
388    
389                                    throw new FileSizeException(uploadException.getCause());
390                            }
391                            else {
392                                    throw e;
393                            }
394                    }
395                    finally {
396                            StreamUtil.cleanUp(inputStream);
397                    }
398            }
399    
400            protected void cancelFileEntriesCheckOut(ActionRequest actionRequest)
401                    throws Exception {
402    
403                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
404    
405                    if (fileEntryId > 0) {
406                            DLAppServiceUtil.cancelCheckOut(fileEntryId);
407                    }
408                    else {
409                            long[] fileEntryIds = StringUtil.split(
410                                    ParamUtil.getString(actionRequest, "fileEntryIds"), 0L);
411    
412                            for (int i = 0; i < fileEntryIds.length; i++) {
413                                    DLAppServiceUtil.cancelCheckOut(fileEntryIds[i]);
414                            }
415                    }
416            }
417    
418            protected void checkInFileEntries(ActionRequest actionRequest)
419                    throws Exception {
420    
421                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
422    
423                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
424                            actionRequest);
425    
426                    if (fileEntryId > 0) {
427                            DLAppServiceUtil.checkInFileEntry(
428                                    fileEntryId, false, StringPool.BLANK, serviceContext);
429                    }
430                    else {
431                            long[] fileEntryIds = StringUtil.split(
432                                    ParamUtil.getString(actionRequest, "fileEntryIds"), 0L);
433    
434                            for (int i = 0; i < fileEntryIds.length; i++) {
435                                    DLAppServiceUtil.checkInFileEntry(
436                                            fileEntryIds[i], false, StringPool.BLANK, serviceContext);
437                            }
438                    }
439            }
440    
441            protected void checkOutFileEntries(ActionRequest actionRequest)
442                    throws Exception {
443    
444                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
445    
446                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
447                            actionRequest);
448    
449                    if (fileEntryId > 0) {
450                            DLAppServiceUtil.checkOutFileEntry(fileEntryId, serviceContext);
451                    }
452                    else {
453                            long[] fileEntryIds = StringUtil.split(
454                                    ParamUtil.getString(actionRequest, "fileEntryIds"), 0L);
455    
456                            for (int i = 0; i < fileEntryIds.length; i++) {
457                                    DLAppServiceUtil.checkOutFileEntry(
458                                            fileEntryIds[i], serviceContext);
459                            }
460                    }
461            }
462    
463            protected void deleteFileEntry(
464                            LiferayPortletConfig liferayPortletConfig,
465                            ActionRequest actionRequest, boolean moveToTrash)
466                    throws Exception {
467    
468                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
469    
470                    if (fileEntryId == 0) {
471                            return;
472                    }
473    
474                    String version = ParamUtil.getString(actionRequest, "version");
475    
476                    if (Validator.isNotNull(version)) {
477                            DLAppServiceUtil.deleteFileVersion(fileEntryId, version);
478    
479                            return;
480                    }
481    
482                    if (!moveToTrash) {
483                            DLAppServiceUtil.deleteFileEntry(fileEntryId);
484    
485                            return;
486                    }
487    
488                    DLAppServiceUtil.moveFileEntryToTrash(fileEntryId);
489    
490                    Map<String, String[]> data = new HashMap<String, String[]>();
491    
492                    data.put(
493                            "restoreFileEntryIds", new String[] {String.valueOf(fileEntryId)});
494    
495                    SessionMessages.add(
496                            actionRequest,
497                            liferayPortletConfig.getPortletId() +
498                                    SessionMessages.KEY_SUFFIX_DELETE_SUCCESS_DATA,
499                            data);
500    
501                    SessionMessages.add(
502                            actionRequest,
503                            liferayPortletConfig.getPortletId() +
504                                    SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE);
505            }
506    
507            protected void deleteTempFileEntry(
508                            ActionRequest actionRequest, ActionResponse actionResponse)
509                    throws Exception {
510    
511                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
512                            WebKeys.THEME_DISPLAY);
513    
514                    long folderId = ParamUtil.getLong(actionRequest, "folderId");
515                    String fileName = ParamUtil.getString(actionRequest, "fileName");
516    
517                    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
518    
519                    try {
520                            DLAppServiceUtil.deleteTempFileEntry(
521                                    themeDisplay.getScopeGroupId(), folderId, fileName,
522                                    _TEMP_FOLDER_NAME);
523    
524                            jsonObject.put("deleted", Boolean.TRUE);
525                    }
526                    catch (Exception e) {
527                            String errorMessage = LanguageUtil.get(
528                                    themeDisplay.getLocale(),
529                                    "an-unexpected-error-occurred-while-deleting-the-file");
530    
531                            jsonObject.put("deleted", Boolean.FALSE);
532                            jsonObject.put("errorMessage", errorMessage);
533                    }
534    
535                    writeJSON(actionRequest, actionResponse, jsonObject);
536            }
537    
538            protected String getAddMultipleFileEntriesErrorMessage(
539                            ThemeDisplay themeDisplay, Exception e)
540                    throws Exception {
541    
542                    String errorMessage = null;
543    
544                    if (e instanceof AssetCategoryException) {
545                            AssetCategoryException ace = (AssetCategoryException)e;
546    
547                            AssetVocabulary assetVocabulary = ace.getVocabulary();
548    
549                            String vocabularyTitle = StringPool.BLANK;
550    
551                            if (assetVocabulary != null) {
552                                    vocabularyTitle = assetVocabulary.getTitle(
553                                            themeDisplay.getLocale());
554                            }
555    
556                            if (ace.getType() == AssetCategoryException.AT_LEAST_ONE_CATEGORY) {
557                                    errorMessage = LanguageUtil.format(
558                                            themeDisplay.getLocale(),
559                                            "please-select-at-least-one-category-for-x",
560                                            vocabularyTitle);
561                            }
562                            else if (ace.getType() ==
563                                                    AssetCategoryException.TOO_MANY_CATEGORIES) {
564    
565                                    errorMessage = LanguageUtil.format(
566                                            themeDisplay.getLocale(),
567                                            "you-cannot-select-more-than-one-category-for-x",
568                                            vocabularyTitle);
569                            }
570                    }
571                    else if (e instanceof DuplicateFileException) {
572                            errorMessage = LanguageUtil.get(
573                                    themeDisplay.getLocale(),
574                                    "the-folder-you-selected-already-has-an-entry-with-this-name." +
575                                            "-please-select-a-different-folder");
576                    }
577                    else if (e instanceof FileExtensionException) {
578                            errorMessage = LanguageUtil.format(
579                                    themeDisplay.getLocale(),
580                                    "please-enter-a-file-with-a-valid-extension-x",
581                                    StringUtil.merge(
582                                            PrefsPropsUtil.getStringArray(
583                                                    PropsKeys.DL_FILE_EXTENSIONS, StringPool.COMMA)));
584                    }
585                    else if (e instanceof FileNameException) {
586                            errorMessage = LanguageUtil.get(
587                                    themeDisplay.getLocale(),
588                                    "please-enter-a-file-with-a-valid-file-name");
589                    }
590                    else if (e instanceof FileSizeException) {
591                            long maxSizeMB = PrefsPropsUtil.getLong(
592                                    PropsKeys.DL_FILE_MAX_SIZE) / 1024 / 1024;
593    
594                            errorMessage = LanguageUtil.format(
595                                    themeDisplay.getLocale(),
596                                    "file-size-is-larger-than-x-megabytes", maxSizeMB);
597                    }
598                    else if (e instanceof InvalidFileEntryTypeException) {
599                            errorMessage = LanguageUtil.get(
600                                    themeDisplay.getLocale(),
601                                    "the-document-type-you-selected-is-not-valid-for-this-folder");
602                    }
603                    else {
604                            errorMessage = LanguageUtil.get(
605                                    themeDisplay.getLocale(),
606                                    "an-unexpected-error-occurred-while-saving-your-document");
607                    }
608    
609                    return errorMessage;
610            }
611    
612            protected void handleUploadException(
613                            ActionRequest actionRequest, ActionResponse actionResponse,
614                            String cmd, Exception e)
615                    throws Exception {
616    
617                    if (e instanceof AssetCategoryException ||
618                            e instanceof AssetTagException) {
619    
620                            SessionErrors.add(actionRequest, e.getClass(), e);
621                    }
622                    else if (e instanceof DuplicateFileException ||
623                                     e instanceof DuplicateFolderNameException ||
624                                     e instanceof FileExtensionException ||
625                                     e instanceof FileMimeTypeException ||
626                                     e instanceof FileNameException ||
627                                     e instanceof FileSizeException ||
628                                     e instanceof NoSuchFolderException ||
629                                     e instanceof SourceFileNameException ||
630                                     e instanceof StorageFieldRequiredException) {
631    
632                            if (!cmd.equals(Constants.ADD_DYNAMIC) &&
633                                    !cmd.equals(Constants.ADD_MULTIPLE) &&
634                                    !cmd.equals(Constants.ADD_TEMP)) {
635    
636                                    SessionErrors.add(actionRequest, e.getClass());
637    
638                                    return;
639                            }
640    
641                            if (e instanceof DuplicateFileException ||
642                                    e instanceof FileExtensionException ||
643                                    e instanceof FileNameException ||
644                                    e instanceof FileSizeException) {
645    
646                                    HttpServletResponse response =
647                                            PortalUtil.getHttpServletResponse(actionResponse);
648    
649                                    response.setContentType(ContentTypes.TEXT_HTML);
650                                    response.setStatus(HttpServletResponse.SC_OK);
651    
652                                    int errorType = 0;
653    
654                                    if (e instanceof DuplicateFileException) {
655                                            errorType =
656                                                    ServletResponseConstants.SC_DUPLICATE_FILE_EXCEPTION;
657                                    }
658                                    else if (e instanceof FileExtensionException) {
659                                            errorType =
660                                                    ServletResponseConstants.SC_FILE_EXTENSION_EXCEPTION;
661                                    }
662                                    else if (e instanceof FileNameException) {
663                                            errorType = ServletResponseConstants.SC_FILE_NAME_EXCEPTION;
664                                    }
665                                    else if (e instanceof FileSizeException) {
666                                            errorType = ServletResponseConstants.SC_FILE_SIZE_EXCEPTION;
667                                    }
668    
669                                    ServletResponseUtil.write(response, String.valueOf(errorType));
670                            }
671    
672                            SessionErrors.add(actionRequest, e.getClass());
673                    }
674                    else if (e instanceof DuplicateLockException ||
675                                     e instanceof InvalidFileVersionException ||
676                                     e instanceof NoSuchFileEntryException ||
677                                     e instanceof PrincipalException) {
678    
679                            if (e instanceof DuplicateLockException) {
680                                    DuplicateLockException dle = (DuplicateLockException)e;
681    
682                                    SessionErrors.add(actionRequest, dle.getClass(), dle.getLock());
683                            }
684                            else {
685                                    SessionErrors.add(actionRequest, e.getClass());
686                            }
687    
688                            setForward(actionRequest, "portlet.document_library.error");
689                    }
690                    else {
691                            throw e;
692                    }
693            }
694    
695            protected void moveFileEntries(
696                            ActionRequest actionRequest, boolean moveFromTrash)
697                    throws Exception {
698    
699                    long[] fileEntryIds = null;
700    
701                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
702    
703                    if (fileEntryId > 0) {
704                            fileEntryIds = new long[] {fileEntryId};
705                    }
706                    else {
707                            fileEntryIds = StringUtil.split(
708                                    ParamUtil.getString(actionRequest, "fileEntryIds"), 0L);
709                    }
710    
711                    long newFolderId = ParamUtil.getLong(actionRequest, "newFolderId");
712    
713                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
714                            DLFileEntry.class.getName(), actionRequest);
715    
716                    for (long moveFileEntryId : fileEntryIds) {
717                            if (moveFromTrash) {
718                                    DLAppServiceUtil.moveFileEntryFromTrash(
719                                            moveFileEntryId, newFolderId, serviceContext);
720                            }
721    
722                            else {
723                                    DLAppServiceUtil.moveFileEntry(
724                                            moveFileEntryId, newFolderId, serviceContext);
725                            }
726                    }
727            }
728    
729            protected void revertFileEntry(ActionRequest actionRequest)
730                    throws Exception {
731    
732                    long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId");
733                    String version = ParamUtil.getString(actionRequest, "version");
734    
735                    ServiceContext serviceContext = ServiceContextFactory.getInstance(
736                            DLFileEntry.class.getName(), actionRequest);
737    
738                    DLAppServiceUtil.revertFileEntry(fileEntryId, version, serviceContext);
739            }
740    
741            protected void updateFileEntry(
742                            PortletConfig portletConfig, ActionRequest actionRequest,
743                            ActionResponse actionResponse)
744                    throws Exception {
745    
746                    UploadPortletRequest uploadPortletRequest =
747                            PortalUtil.getUploadPortletRequest(actionRequest);
748    
749                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
750                            WebKeys.THEME_DISPLAY);
751    
752                    String cmd = ParamUtil.getString(uploadPortletRequest, Constants.CMD);
753    
754                    long fileEntryId = ParamUtil.getLong(
755                            uploadPortletRequest, "fileEntryId");
756    
757                    long repositoryId = ParamUtil.getLong(
758                            uploadPortletRequest, "repositoryId");
759                    long folderId = ParamUtil.getLong(uploadPortletRequest, "folderId");
760                    String sourceFileName = uploadPortletRequest.getFileName("file");
761                    String title = ParamUtil.getString(uploadPortletRequest, "title");
762                    String description = ParamUtil.getString(
763                            uploadPortletRequest, "description");
764                    String changeLog = ParamUtil.getString(
765                            uploadPortletRequest, "changeLog");
766                    boolean majorVersion = ParamUtil.getBoolean(
767                            uploadPortletRequest, "majorVersion");
768    
769                    if (folderId > 0) {
770                            Folder folder = DLAppServiceUtil.getFolder(folderId);
771    
772                            if (folder.getGroupId() != themeDisplay.getScopeGroupId()) {
773                                    throw new NoSuchFolderException();
774                            }
775                    }
776    
777                    InputStream inputStream = null;
778    
779                    try {
780                            String contentType = uploadPortletRequest.getContentType("file");
781    
782                            long size = uploadPortletRequest.getSize("file");
783    
784                            if ((cmd.equals(Constants.ADD) ||
785                                     cmd.equals(Constants.ADD_DYNAMIC)) &&
786                                    (size == 0)) {
787    
788                                    contentType = MimeTypesUtil.getContentType(title);
789                            }
790    
791                            if (cmd.equals(Constants.ADD) ||
792                                    cmd.equals(Constants.ADD_DYNAMIC) || (size > 0)) {
793    
794                                    String portletName = portletConfig.getPortletName();
795    
796                                    if (portletName.equals(PortletKeys.MEDIA_GALLERY_DISPLAY)) {
797                                            String portletResource = ParamUtil.getString(
798                                                    actionRequest, "portletResource");
799    
800                                            PortletPreferences portletPreferences = null;
801    
802                                            if (Validator.isNotNull(portletResource)) {
803                                                    PortletPreferencesFactoryUtil.getPortletSetup(
804                                                            actionRequest, portletResource);
805                                            }
806                                            else {
807                                                    portletPreferences = actionRequest.getPreferences();
808                                            }
809    
810                                            String[] mimeTypes = DLUtil.getMediaGalleryMimeTypes(
811                                                    portletPreferences, actionRequest);
812    
813                                            if (Arrays.binarySearch(mimeTypes, contentType) < 0) {
814                                                    throw new FileMimeTypeException(contentType);
815                                            }
816                                    }
817                            }
818    
819                            inputStream = uploadPortletRequest.getFileAsStream("file");
820    
821                            ServiceContext serviceContext = ServiceContextFactory.getInstance(
822                                    DLFileEntry.class.getName(), uploadPortletRequest);
823    
824                            FileEntry fileEntry = null;
825    
826                            if (cmd.equals(Constants.ADD) ||
827                                    cmd.equals(Constants.ADD_DYNAMIC)) {
828    
829                                    // Add file entry
830    
831                                    fileEntry = DLAppServiceUtil.addFileEntry(
832                                            repositoryId, folderId, sourceFileName, contentType, title,
833                                            description, changeLog, inputStream, size, serviceContext);
834    
835                                    AssetPublisherUtil.addAndStoreSelection(
836                                            actionRequest, DLFileEntry.class.getName(),
837                                            fileEntry.getFileEntryId(), -1);
838    
839                                    if (cmd.equals(Constants.ADD_DYNAMIC)) {
840                                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
841    
842                                            jsonObject.put("fileEntryId", fileEntry.getFileEntryId());
843    
844                                            writeJSON(actionRequest, actionResponse, jsonObject);
845                                    }
846                            }
847                            else if (cmd.equals(Constants.UPDATE_AND_CHECKIN)) {
848    
849                                    // Update file entry and checkin
850    
851                                    fileEntry = DLAppServiceUtil.updateFileEntryAndCheckIn(
852                                            fileEntryId, sourceFileName, contentType, title,
853                                            description, changeLog, majorVersion, inputStream, size,
854                                            serviceContext);
855                            }
856                            else {
857    
858                                    // Update file entry
859    
860                                    fileEntry = DLAppServiceUtil.updateFileEntry(
861                                            fileEntryId, sourceFileName, contentType, title,
862                                            description, changeLog, majorVersion, inputStream, size,
863                                            serviceContext);
864                            }
865    
866                            AssetPublisherUtil.addRecentFolderId(
867                                    actionRequest, DLFileEntry.class.getName(), folderId);
868                    }
869                    catch (Exception e) {
870                            UploadException uploadException =
871                                    (UploadException)actionRequest.getAttribute(
872                                            WebKeys.UPLOAD_EXCEPTION);
873    
874                            if ((uploadException != null) &&
875                                    uploadException.isExceededSizeLimit()) {
876    
877                                    throw new FileSizeException(uploadException.getCause());
878                            }
879    
880                            throw e;
881                    }
882                    finally {
883                            StreamUtil.cleanUp(inputStream);
884                    }
885            }
886    
887            private static final String _TEMP_FOLDER_NAME =
888                    EditFileEntryAction.class.getName();
889    
890    }