001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.documentlibrary.service.impl;
016    
017    import com.liferay.portal.kernel.bean.BeanReference;
018    import com.liferay.portal.kernel.comment.CommentManagerUtil;
019    import com.liferay.portal.kernel.dao.orm.ActionableDynamicQuery;
020    import com.liferay.portal.kernel.dao.orm.DynamicQuery;
021    import com.liferay.portal.kernel.dao.orm.IndexableActionableDynamicQuery;
022    import com.liferay.portal.kernel.dao.orm.Property;
023    import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
024    import com.liferay.portal.kernel.dao.orm.QueryDefinition;
025    import com.liferay.portal.kernel.dao.orm.QueryUtil;
026    import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
027    import com.liferay.portal.kernel.exception.PortalException;
028    import com.liferay.portal.kernel.exception.SystemException;
029    import com.liferay.portal.kernel.image.ImageBag;
030    import com.liferay.portal.kernel.image.ImageToolUtil;
031    import com.liferay.portal.kernel.increment.BufferedIncrement;
032    import com.liferay.portal.kernel.increment.NumberIncrement;
033    import com.liferay.portal.kernel.interval.IntervalActionProcessor;
034    import com.liferay.portal.kernel.language.LanguageUtil;
035    import com.liferay.portal.kernel.lock.ExpiredLockException;
036    import com.liferay.portal.kernel.lock.InvalidLockException;
037    import com.liferay.portal.kernel.lock.Lock;
038    import com.liferay.portal.kernel.lock.LockManagerUtil;
039    import com.liferay.portal.kernel.lock.NoSuchLockException;
040    import com.liferay.portal.kernel.log.Log;
041    import com.liferay.portal.kernel.log.LogFactoryUtil;
042    import com.liferay.portal.kernel.repository.event.RepositoryEventTrigger;
043    import com.liferay.portal.kernel.repository.event.RepositoryEventType;
044    import com.liferay.portal.kernel.repository.model.FileEntry;
045    import com.liferay.portal.kernel.search.Document;
046    import com.liferay.portal.kernel.search.Field;
047    import com.liferay.portal.kernel.search.Hits;
048    import com.liferay.portal.kernel.search.Indexable;
049    import com.liferay.portal.kernel.search.IndexableType;
050    import com.liferay.portal.kernel.search.Indexer;
051    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
052    import com.liferay.portal.kernel.search.SearchContext;
053    import com.liferay.portal.kernel.search.SearchException;
054    import com.liferay.portal.kernel.search.Sort;
055    import com.liferay.portal.kernel.systemevent.SystemEvent;
056    import com.liferay.portal.kernel.util.ArrayUtil;
057    import com.liferay.portal.kernel.util.Constants;
058    import com.liferay.portal.kernel.util.DateRange;
059    import com.liferay.portal.kernel.util.DigesterUtil;
060    import com.liferay.portal.kernel.util.FileUtil;
061    import com.liferay.portal.kernel.util.GetterUtil;
062    import com.liferay.portal.kernel.util.OrderByComparator;
063    import com.liferay.portal.kernel.util.ParamUtil;
064    import com.liferay.portal.kernel.util.PropsKeys;
065    import com.liferay.portal.kernel.util.StreamUtil;
066    import com.liferay.portal.kernel.util.StringBundler;
067    import com.liferay.portal.kernel.util.StringPool;
068    import com.liferay.portal.kernel.util.StringUtil;
069    import com.liferay.portal.kernel.util.UnicodeProperties;
070    import com.liferay.portal.kernel.util.Validator;
071    import com.liferay.portal.kernel.workflow.WorkflowConstants;
072    import com.liferay.portal.model.Group;
073    import com.liferay.portal.model.Image;
074    import com.liferay.portal.model.ModelHintsUtil;
075    import com.liferay.portal.model.Repository;
076    import com.liferay.portal.model.ResourceConstants;
077    import com.liferay.portal.model.SystemEventConstants;
078    import com.liferay.portal.model.User;
079    import com.liferay.portal.repository.liferayrepository.model.LiferayFileEntry;
080    import com.liferay.portal.repository.liferayrepository.model.LiferayFileVersion;
081    import com.liferay.portal.security.auth.PrincipalThreadLocal;
082    import com.liferay.portal.service.ServiceContext;
083    import com.liferay.portal.util.PortalUtil;
084    import com.liferay.portal.util.PrefsPropsUtil;
085    import com.liferay.portal.util.PropsValues;
086    import com.liferay.portal.util.RepositoryUtil;
087    import com.liferay.portlet.documentlibrary.DuplicateFileEntryException;
088    import com.liferay.portlet.documentlibrary.DuplicateFolderNameException;
089    import com.liferay.portlet.documentlibrary.FileExtensionException;
090    import com.liferay.portlet.documentlibrary.FileNameException;
091    import com.liferay.portlet.documentlibrary.ImageSizeException;
092    import com.liferay.portlet.documentlibrary.InvalidFileEntryTypeException;
093    import com.liferay.portlet.documentlibrary.InvalidFileVersionException;
094    import com.liferay.portlet.documentlibrary.NoSuchFileEntryException;
095    import com.liferay.portlet.documentlibrary.model.DLFileEntry;
096    import com.liferay.portlet.documentlibrary.model.DLFileEntryConstants;
097    import com.liferay.portlet.documentlibrary.model.DLFileEntryMetadata;
098    import com.liferay.portlet.documentlibrary.model.DLFileEntryType;
099    import com.liferay.portlet.documentlibrary.model.DLFileVersion;
100    import com.liferay.portlet.documentlibrary.model.DLFolder;
101    import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
102    import com.liferay.portlet.documentlibrary.model.impl.DLFileEntryImpl;
103    import com.liferay.portlet.documentlibrary.service.DLFileEntryService;
104    import com.liferay.portlet.documentlibrary.service.base.DLFileEntryLocalServiceBaseImpl;
105    import com.liferay.portlet.documentlibrary.store.DLStoreUtil;
106    import com.liferay.portlet.documentlibrary.util.DL;
107    import com.liferay.portlet.documentlibrary.util.DLAppUtil;
108    import com.liferay.portlet.documentlibrary.util.DLUtil;
109    import com.liferay.portlet.documentlibrary.util.DLValidatorUtil;
110    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelModifiedDateComparator;
111    import com.liferay.portlet.dynamicdatamapping.DDMFormValues;
112    import com.liferay.portlet.dynamicdatamapping.DDMStructure;
113    import com.liferay.portlet.dynamicdatamapping.DDMStructureManagerUtil;
114    import com.liferay.portlet.dynamicdatamapping.StorageEngineManagerUtil;
115    import com.liferay.portlet.expando.model.ExpandoBridge;
116    import com.liferay.portlet.expando.model.ExpandoColumnConstants;
117    import com.liferay.portlet.expando.model.ExpandoRow;
118    import com.liferay.portlet.expando.model.ExpandoTable;
119    import com.liferay.portlet.expando.util.ExpandoBridgeUtil;
120    import com.liferay.portlet.exportimport.lar.ExportImportThreadLocal;
121    
122    import java.awt.image.RenderedImage;
123    
124    import java.io.File;
125    import java.io.IOException;
126    import java.io.InputStream;
127    import java.io.Serializable;
128    
129    import java.util.ArrayList;
130    import java.util.Collections;
131    import java.util.Date;
132    import java.util.HashMap;
133    import java.util.List;
134    import java.util.Map;
135    
136    /**
137     * Provides the local service for accessing, adding, checking in/out, deleting,
138     * locking/unlocking, moving, reverting, updating, and verifying document
139     * library file entries.
140     *
141     * <p>
142     * Due to legacy code, the names of some file entry properties are not
143     * intuitive. Each file entry has both a name and title. The <code>name</code>
144     * is a unique identifier for a given file and is generally numeric, whereas the
145     * <code>title</code> is the actual name specified by the user (such as
146     * &quot;Budget.xls&quot;).
147     * </p>
148     *
149     * @author Brian Wing Shun Chan
150     * @author Harry Mark
151     * @author Alexander Chow
152     * @author Manuel de la Pe??a
153     */
154    public class DLFileEntryLocalServiceImpl
155            extends DLFileEntryLocalServiceBaseImpl {
156    
157            @Override
158            public DLFileEntry addFileEntry(
159                            long userId, long groupId, long repositoryId, long folderId,
160                            String sourceFileName, String mimeType, String title,
161                            String description, String changeLog, long fileEntryTypeId,
162                            Map<String, DDMFormValues> ddmFormValuesMap, File file,
163                            InputStream is, long size, ServiceContext serviceContext)
164                    throws PortalException {
165    
166                    if (Validator.isNull(title)) {
167                            if (Validator.isNull(sourceFileName)) {
168                                    throw new FileNameException("Title is null");
169                            }
170                            else {
171                                    title = sourceFileName;
172                            }
173                    }
174    
175                    // File entry
176    
177                    User user = userPersistence.findByPrimaryKey(userId);
178                    folderId = dlFolderLocalService.getFolderId(
179                            user.getCompanyId(), folderId);
180                    String name = String.valueOf(
181                            counterLocalService.increment(DLFileEntry.class.getName()));
182                    String extension = DLAppUtil.getExtension(title, sourceFileName);
183    
184                    String fileName = DLUtil.getSanitizedFileName(title, extension);
185    
186                    if (fileEntryTypeId == -1) {
187                            fileEntryTypeId =
188                                    dlFileEntryTypeLocalService.getDefaultFileEntryTypeId(folderId);
189                    }
190    
191                    validateFileEntryTypeId(
192                            PortalUtil.getCurrentAndAncestorSiteGroupIds(groupId), folderId,
193                            fileEntryTypeId);
194    
195                    validateFile(
196                            groupId, folderId, 0, sourceFileName, fileName, extension, title);
197    
198                    long fileEntryId = counterLocalService.increment();
199    
200                    DLFileEntry dlFileEntry = dlFileEntryPersistence.create(fileEntryId);
201    
202                    dlFileEntry.setUuid(serviceContext.getUuid());
203                    dlFileEntry.setGroupId(groupId);
204                    dlFileEntry.setCompanyId(user.getCompanyId());
205                    dlFileEntry.setUserId(user.getUserId());
206                    dlFileEntry.setUserName(user.getFullName());
207    
208                    DLFolder repositoryDLFolder = null;
209    
210                    if (repositoryId != groupId) {
211                            Repository repository = repositoryLocalService.getRepository(
212                                    repositoryId);
213    
214                            repositoryDLFolder = dlFolderPersistence.findByPrimaryKey(
215                                    repository.getDlFolderId());
216                    }
217    
218                    long classNameId = 0;
219                    long classPK = 0;
220    
221                    if ((repositoryDLFolder != null) && repositoryDLFolder.isHidden()) {
222                            classNameId = classNameLocalService.getClassNameId(
223                                    (String)serviceContext.getAttribute("className"));
224                            classPK = ParamUtil.getLong(serviceContext, "classPK");
225                    }
226    
227                    dlFileEntry.setClassNameId(classNameId);
228                    dlFileEntry.setClassPK(classPK);
229                    dlFileEntry.setRepositoryId(repositoryId);
230                    dlFileEntry.setFolderId(folderId);
231                    dlFileEntry.setTreePath(dlFileEntry.buildTreePath());
232                    dlFileEntry.setName(name);
233                    dlFileEntry.setFileName(fileName);
234                    dlFileEntry.setExtension(extension);
235                    dlFileEntry.setMimeType(mimeType);
236                    dlFileEntry.setTitle(title);
237                    dlFileEntry.setDescription(description);
238                    dlFileEntry.setFileEntryTypeId(fileEntryTypeId);
239                    dlFileEntry.setVersion(DLFileEntryConstants.VERSION_DEFAULT);
240                    dlFileEntry.setSize(size);
241                    dlFileEntry.setReadCount(DLFileEntryConstants.DEFAULT_READ_COUNT);
242    
243                    dlFileEntryPersistence.update(dlFileEntry);
244    
245                    // File version
246    
247                    addFileVersion(
248                            user, dlFileEntry, fileName, extension, mimeType, title,
249                            description, changeLog, StringPool.BLANK, fileEntryTypeId,
250                            ddmFormValuesMap, DLFileEntryConstants.VERSION_DEFAULT, size,
251                            WorkflowConstants.STATUS_DRAFT, serviceContext);
252    
253                    // Folder
254    
255                    if (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
256                            dlFolderLocalService.updateLastPostDate(
257                                    dlFileEntry.getFolderId(), dlFileEntry.getModifiedDate());
258                    }
259    
260                    // File
261    
262                    if (file != null) {
263                            DLStoreUtil.addFile(
264                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(), name,
265                                    false, file);
266                    }
267                    else {
268                            DLStoreUtil.addFile(
269                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(), name,
270                                    false, is);
271                    }
272    
273                    return dlFileEntry;
274            }
275    
276            @Override
277            public DLFileVersion cancelCheckOut(long userId, long fileEntryId)
278                    throws PortalException {
279    
280                    if (!isFileEntryCheckedOut(fileEntryId)) {
281                            return null;
282                    }
283    
284                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
285                            fileEntryId);
286    
287                    DLFileVersion dlFileVersion =
288                            dlFileVersionLocalService.getLatestFileVersion(fileEntryId, false);
289    
290                    removeFileVersion(dlFileEntry, dlFileVersion);
291    
292                    return dlFileVersion;
293            }
294    
295            @Override
296            public void checkInFileEntry(
297                            long userId, long fileEntryId, boolean majorVersion,
298                            String changeLog, ServiceContext serviceContext)
299                    throws PortalException {
300    
301                    if (!isFileEntryCheckedOut(fileEntryId)) {
302                            return;
303                    }
304    
305                    User user = userPersistence.findByPrimaryKey(userId);
306    
307                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
308                            fileEntryId);
309    
310                    boolean webDAVCheckInMode = GetterUtil.getBoolean(
311                            serviceContext.getAttribute(DL.WEBDAV_CHECK_IN_MODE));
312    
313                    boolean manualCheckInRequired = dlFileEntry.getManualCheckInRequired();
314    
315                    if (!webDAVCheckInMode && manualCheckInRequired) {
316                            dlFileEntry.setManualCheckInRequired(false);
317    
318                            dlFileEntryPersistence.update(dlFileEntry);
319                    }
320    
321                    DLFileVersion lastDLFileVersion =
322                            dlFileVersionLocalService.getFileVersion(
323                                    dlFileEntry.getFileEntryId(), dlFileEntry.getVersion());
324    
325                    DLFileVersion latestDLFileVersion =
326                            dlFileVersionLocalService.getLatestFileVersion(fileEntryId, false);
327    
328                    if (!majorVersion &&
329                            isKeepFileVersionLabel(
330                                    dlFileEntry, lastDLFileVersion, latestDLFileVersion,
331                                    serviceContext)) {
332    
333                            if (lastDLFileVersion.getSize() != latestDLFileVersion.getSize()) {
334    
335                                    // File entry
336    
337                                    dlFileEntry.setExtension(latestDLFileVersion.getExtension());
338                                    dlFileEntry.setMimeType(latestDLFileVersion.getMimeType());
339                                    dlFileEntry.setSize(latestDLFileVersion.getSize());
340    
341                                    dlFileEntryPersistence.update(dlFileEntry);
342    
343                                    // File version
344    
345                                    lastDLFileVersion.setExtension(
346                                            latestDLFileVersion.getExtension());
347                                    lastDLFileVersion.setMimeType(
348                                            latestDLFileVersion.getMimeType());
349                                    lastDLFileVersion.setSize(latestDLFileVersion.getSize());
350    
351                                    dlFileVersionPersistence.update(lastDLFileVersion);
352    
353                                    // File
354    
355                                    DLStoreUtil.deleteFile(
356                                            user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
357                                            dlFileEntry.getName(), lastDLFileVersion.getVersion());
358    
359                                    DLStoreUtil.copyFileVersion(
360                                            user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
361                                            dlFileEntry.getName(),
362                                            DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION,
363                                            lastDLFileVersion.getVersion());
364                            }
365    
366                            // Latest file version
367    
368                            removeFileVersion(dlFileEntry, latestDLFileVersion);
369                    }
370                    else {
371    
372                            // File version
373    
374                            String version = getNextVersion(
375                                    dlFileEntry, majorVersion, serviceContext.getWorkflowAction());
376    
377                            latestDLFileVersion.setVersion(version);
378                            latestDLFileVersion.setChangeLog(changeLog);
379    
380                            dlFileVersionPersistence.update(latestDLFileVersion);
381    
382                            // Folder
383    
384                            if (dlFileEntry.getFolderId() !=
385                                            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
386    
387                                    dlFolderLocalService.updateLastPostDate(
388                                            dlFileEntry.getFolderId(),
389                                            latestDLFileVersion.getModifiedDate());
390                            }
391    
392                            // File
393    
394                            DLStoreUtil.updateFileVersion(
395                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
396                                    dlFileEntry.getName(),
397                                    DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION, version);
398                    }
399    
400                    unlockFileEntry(fileEntryId);
401            }
402    
403            /**
404             * @deprecated As of 6.2.0, replaced by {@link #checkInFileEntry(long, long,
405             *             String, ServiceContext)}
406             */
407            @Deprecated
408            @Override
409            public void checkInFileEntry(long userId, long fileEntryId, String lockUuid)
410                    throws PortalException {
411    
412                    checkInFileEntry(userId, fileEntryId, lockUuid, new ServiceContext());
413            }
414    
415            @Override
416            public void checkInFileEntry(
417                            long userId, long fileEntryId, String lockUuid,
418                            ServiceContext serviceContext)
419                    throws PortalException {
420    
421                    if (Validator.isNotNull(lockUuid)) {
422                            try {
423                                    Lock lock = LockManagerUtil.getLock(
424                                            DLFileEntry.class.getName(), fileEntryId);
425    
426                                    if (!Validator.equals(lock.getUuid(), lockUuid)) {
427                                            throw new InvalidLockException("UUIDs do not match");
428                                    }
429                            }
430                            catch (PortalException pe) {
431                                    if ((pe instanceof ExpiredLockException) ||
432                                            (pe instanceof NoSuchLockException)) {
433                                    }
434                                    else {
435                                            throw pe;
436                                    }
437                            }
438                    }
439    
440                    checkInFileEntry(
441                            userId, fileEntryId, false, StringPool.BLANK, serviceContext);
442            }
443    
444            /**
445             * @deprecated As of 6.2.0, replaced by {@link #checkOutFileEntry(long,
446             *             long, ServiceContext)}
447             */
448            @Deprecated
449            @Override
450            public DLFileEntry checkOutFileEntry(long userId, long fileEntryId)
451                    throws PortalException {
452    
453                    return checkOutFileEntry(userId, fileEntryId, new ServiceContext());
454            }
455    
456            @Override
457            public DLFileEntry checkOutFileEntry(
458                            long userId, long fileEntryId, ServiceContext serviceContext)
459                    throws PortalException {
460    
461                    return checkOutFileEntry(
462                            userId, fileEntryId, StringPool.BLANK,
463                            DLFileEntryImpl.LOCK_EXPIRATION_TIME, serviceContext);
464            }
465    
466            /**
467             * @deprecated As of 6.2.0, replaced by {@link #checkOutFileEntry(long,
468             *             long, String, long, ServiceContext)}
469             */
470            @Deprecated
471            @Override
472            public DLFileEntry checkOutFileEntry(
473                            long userId, long fileEntryId, String owner, long expirationTime)
474                    throws PortalException {
475    
476                    return checkOutFileEntry(
477                            userId, fileEntryId, owner, expirationTime, new ServiceContext());
478            }
479    
480            @Override
481            public DLFileEntry checkOutFileEntry(
482                            long userId, long fileEntryId, String owner, long expirationTime,
483                            ServiceContext serviceContext)
484                    throws PortalException {
485    
486                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
487                            fileEntryId);
488    
489                    boolean hasLock = hasFileEntryLock(userId, fileEntryId);
490    
491                    if (!hasLock) {
492                            if ((expirationTime <= 0) ||
493                                    (expirationTime > DLFileEntryImpl.LOCK_EXPIRATION_TIME)) {
494    
495                                    expirationTime = DLFileEntryImpl.LOCK_EXPIRATION_TIME;
496                            }
497    
498                            LockManagerUtil.lock(
499                                    userId, DLFileEntry.class.getName(), fileEntryId, owner, false,
500                                    expirationTime);
501                    }
502    
503                    User user = userPersistence.findByPrimaryKey(userId);
504    
505                    serviceContext.setCompanyId(user.getCompanyId());
506    
507                    DLFileVersion dlFileVersion =
508                            dlFileVersionLocalService.getLatestFileVersion(fileEntryId, false);
509    
510                    long dlFileVersionId = dlFileVersion.getFileVersionId();
511    
512                    serviceContext.setUserId(userId);
513    
514                    boolean manualCheckinRequired = GetterUtil.getBoolean(
515                            serviceContext.getAttribute(DL.MANUAL_CHECK_IN_REQUIRED));
516    
517                    dlFileEntry.setManualCheckInRequired(manualCheckinRequired);
518    
519                    dlFileEntryPersistence.update(dlFileEntry);
520    
521                    String version = dlFileVersion.getVersion();
522    
523                    if (!version.equals(
524                                    DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION)) {
525    
526                            long existingDLFileVersionId = ParamUtil.getLong(
527                                    serviceContext, "existingDLFileVersionId");
528    
529                            if (existingDLFileVersionId > 0) {
530                                    DLFileVersion existingDLFileVersion =
531                                            dlFileVersionPersistence.findByPrimaryKey(
532                                                    existingDLFileVersionId);
533    
534                                    dlFileVersion = updateFileVersion(
535                                            user, existingDLFileVersion, null,
536                                            existingDLFileVersion.getFileName(),
537                                            existingDLFileVersion.getExtension(),
538                                            existingDLFileVersion.getMimeType(),
539                                            existingDLFileVersion.getTitle(),
540                                            existingDLFileVersion.getDescription(),
541                                            existingDLFileVersion.getChangeLog(),
542                                            existingDLFileVersion.getExtraSettings(),
543                                            existingDLFileVersion.getFileEntryTypeId(), null,
544                                            DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION,
545                                            existingDLFileVersion.getSize(),
546                                            WorkflowConstants.STATUS_DRAFT,
547                                            serviceContext.getModifiedDate(null), serviceContext);
548                            }
549                            else {
550                                    long oldDLFileVersionId = dlFileVersion.getFileVersionId();
551    
552                                    dlFileVersion = addFileVersion(
553                                            user, dlFileEntry, dlFileVersion.getFileName(),
554                                            dlFileVersion.getExtension(), dlFileVersion.getMimeType(),
555                                            dlFileVersion.getTitle(), dlFileVersion.getDescription(),
556                                            dlFileVersion.getChangeLog(),
557                                            dlFileVersion.getExtraSettings(),
558                                            dlFileVersion.getFileEntryTypeId(), null,
559                                            DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION,
560                                            dlFileVersion.getSize(), WorkflowConstants.STATUS_DRAFT,
561                                            serviceContext);
562    
563                                    copyExpandoRowModifiedDate(
564                                            dlFileEntry.getCompanyId(), oldDLFileVersionId,
565                                            dlFileVersion.getFileVersionId());
566                            }
567    
568                            if (DLStoreUtil.hasFile(
569                                            dlFileEntry.getCompanyId(),
570                                            dlFileEntry.getDataRepositoryId(), dlFileEntry.getName(),
571                                            DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION)) {
572    
573                                    DLStoreUtil.deleteFile(
574                                            dlFileEntry.getCompanyId(),
575                                            dlFileEntry.getDataRepositoryId(), dlFileEntry.getName(),
576                                            DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION);
577                            }
578    
579                            DLStoreUtil.copyFileVersion(
580                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
581                                    dlFileEntry.getName(), version,
582                                    DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION);
583    
584                            serviceContext.setAttribute("validateDDMFormValues", Boolean.FALSE);
585    
586                            copyFileEntryMetadata(
587                                    dlFileEntry.getCompanyId(), dlFileVersion.getFileEntryTypeId(),
588                                    fileEntryId, dlFileVersionId, dlFileVersion.getFileVersionId(),
589                                    serviceContext);
590    
591                            serviceContext.setAttribute("validateDDMFormValues", Boolean.TRUE);
592                    }
593    
594                    return dlFileEntry;
595            }
596    
597            @Override
598            public void convertExtraSettings(final String[] keys)
599                    throws PortalException {
600    
601                    int total = dlFileEntryFinder.countByExtraSettings();
602    
603                    final IntervalActionProcessor<Void> intervalActionProcessor =
604                            new IntervalActionProcessor<>(total);
605    
606                    intervalActionProcessor.setPerformIntervalActionMethod(
607                            new IntervalActionProcessor.PerformIntervalActionMethod<Void>() {
608    
609                                    @Override
610                                    public Void performIntervalAction(int start, int end)
611                                            throws PortalException {
612    
613                                            List<DLFileEntry> dlFileEntries =
614                                                    dlFileEntryFinder.findByExtraSettings(start, end);
615    
616                                            for (DLFileEntry dlFileEntry : dlFileEntries) {
617                                                    convertExtraSettings(dlFileEntry, keys);
618                                            }
619    
620                                            intervalActionProcessor.incrementStart(
621                                                    dlFileEntries.size());
622    
623                                            return null;
624                                    }
625    
626                            });
627    
628                    intervalActionProcessor.performIntervalActions();
629            }
630    
631            @Override
632            public DLFileEntry copyFileEntry(
633                            long userId, long groupId, long repositoryId, long fileEntryId,
634                            long destFolderId, ServiceContext serviceContext)
635                    throws PortalException {
636    
637                    DLFileEntry dlFileEntry = getFileEntry(fileEntryId);
638    
639                    String sourceFileName = "A";
640    
641                    String extension = dlFileEntry.getExtension();
642    
643                    if (Validator.isNotNull(extension)) {
644                            sourceFileName = sourceFileName.concat(StringPool.PERIOD).concat(
645                                    extension);
646                    }
647    
648                    InputStream inputStream = DLStoreUtil.getFileAsStream(
649                            dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
650                            dlFileEntry.getName());
651    
652                    DLFileEntry newDlFileEntry = addFileEntry(
653                            userId, groupId, repositoryId, destFolderId, sourceFileName,
654                            dlFileEntry.getMimeType(), dlFileEntry.getTitle(),
655                            dlFileEntry.getDescription(), null,
656                            dlFileEntry.getFileEntryTypeId(), null, null, inputStream,
657                            dlFileEntry.getSize(), serviceContext);
658    
659                    DLFileVersion dlFileVersion = dlFileEntry.getFileVersion();
660    
661                    DLFileVersion newDlFileVersion = newDlFileEntry.getFileVersion();
662    
663                    ExpandoBridgeUtil.copyExpandoBridgeAttributes(
664                            dlFileVersion.getExpandoBridge(),
665                            newDlFileVersion.getExpandoBridge());
666    
667                    copyFileEntryMetadata(
668                            dlFileVersion.getCompanyId(), dlFileVersion.getFileEntryTypeId(),
669                            fileEntryId, dlFileVersion.getFileVersionId(),
670                            newDlFileVersion.getFileVersionId(), serviceContext);
671    
672                    return newDlFileEntry;
673            }
674    
675            @Override
676            public void copyFileEntryMetadata(
677                            long companyId, long fileEntryTypeId, long fileEntryId,
678                            long fromFileVersionId, long toFileVersionId,
679                            ServiceContext serviceContext)
680                    throws PortalException {
681    
682                    Map<String, DDMFormValues> ddmFormValuesMap = new HashMap<>();
683    
684                    List<DDMStructure> ddmStructures = null;
685    
686                    if (fileEntryTypeId > 0) {
687                            DLFileEntryType dlFileEntryType =
688                                    dlFileEntryTypeLocalService.getFileEntryType(fileEntryTypeId);
689    
690                            ddmStructures = dlFileEntryType.getDDMStructures();
691                    }
692                    else {
693                            long classNameId = classNameLocalService.getClassNameId(
694                                    DLFileEntryMetadata.class);
695    
696                            ddmStructures = DDMStructureManagerUtil.getClassStructures(
697                                    companyId, classNameId);
698                    }
699    
700                    copyFileEntryMetadata(
701                            companyId, fileEntryId, fromFileVersionId, toFileVersionId,
702                            serviceContext, ddmFormValuesMap, ddmStructures);
703            }
704    
705            @Override
706            public void deleteFileEntries(long groupId, long folderId)
707                    throws PortalException {
708    
709                    deleteFileEntries(groupId, folderId, true);
710            }
711    
712            @Override
713            public void deleteFileEntries(
714                            long groupId, final long folderId,
715                            final boolean includeTrashedEntries)
716                    throws PortalException {
717    
718                    final RepositoryEventTrigger repositoryEventTrigger =
719                            getFolderRepositoryEventTrigger(groupId, folderId);
720    
721                    ActionableDynamicQuery actionableDynamicQuery =
722                            dlFileEntryLocalService.getActionableDynamicQuery();
723    
724                    actionableDynamicQuery.setAddCriteriaMethod(
725                            new ActionableDynamicQuery.AddCriteriaMethod() {
726    
727                                    @Override
728                                    public void addCriteria(DynamicQuery dynamicQuery) {
729                                            Property folderIdproperty = PropertyFactoryUtil.forName(
730                                                    "folderId");
731    
732                                            dynamicQuery.add(folderIdproperty.eq(folderId));
733                                    }
734    
735                            });
736                    actionableDynamicQuery.setGroupId(groupId);
737                    actionableDynamicQuery.setPerformActionMethod(
738                            new ActionableDynamicQuery.PerformActionMethod<DLFileEntry>() {
739    
740                                    @Override
741                                    public void performAction(DLFileEntry dlFileEntry)
742                                            throws PortalException {
743    
744                                            if (includeTrashedEntries ||
745                                                    !dlFileEntry.isInTrashExplicitly()) {
746    
747                                                    repositoryEventTrigger.trigger(
748                                                            RepositoryEventType.Delete.class, FileEntry.class,
749                                                            new LiferayFileEntry(dlFileEntry));
750    
751                                                    dlFileEntryLocalService.deleteFileEntry(dlFileEntry);
752                                            }
753                                    }
754    
755                            });
756    
757                    actionableDynamicQuery.performActions();
758            }
759    
760            @Indexable(type = IndexableType.DELETE)
761            @Override
762            @SystemEvent(
763                    action = SystemEventConstants.ACTION_SKIP,
764                    type = SystemEventConstants.TYPE_DELETE
765            )
766            public DLFileEntry deleteFileEntry(DLFileEntry dlFileEntry)
767                    throws PortalException {
768    
769                    // File entry
770    
771                    dlFileEntryPersistence.remove(dlFileEntry);
772    
773                    // Resources
774    
775                    resourceLocalService.deleteResource(
776                            dlFileEntry.getCompanyId(), DLFileEntry.class.getName(),
777                            ResourceConstants.SCOPE_INDIVIDUAL, dlFileEntry.getFileEntryId());
778    
779                    // WebDAVProps
780    
781                    webDAVPropsLocalService.deleteWebDAVProps(
782                            DLFileEntry.class.getName(), dlFileEntry.getFileEntryId());
783    
784                    // File entry metadata
785    
786                    dlFileEntryMetadataLocalService.deleteFileEntryMetadata(
787                            dlFileEntry.getFileEntryId());
788    
789                    // File versions
790    
791                    List<DLFileVersion> dlFileVersions =
792                            dlFileVersionPersistence.findByFileEntryId(
793                                    dlFileEntry.getFileEntryId());
794    
795                    for (DLFileVersion dlFileVersion : dlFileVersions) {
796                            dlFileVersionPersistence.remove(dlFileVersion);
797    
798                            expandoRowLocalService.deleteRows(dlFileVersion.getFileVersionId());
799    
800                            workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
801                                    dlFileEntry.getCompanyId(), dlFileEntry.getGroupId(),
802                                    DLFileEntry.class.getName(), dlFileVersion.getFileVersionId());
803                    }
804    
805                    // Expando
806    
807                    expandoRowLocalService.deleteRows(dlFileEntry.getFileEntryId());
808    
809                    // Ratings
810    
811                    ratingsStatsLocalService.deleteStats(
812                            DLFileEntry.class.getName(), dlFileEntry.getFileEntryId());
813    
814                    // Lock
815    
816                    unlockFileEntry(dlFileEntry.getFileEntryId());
817    
818                    // File
819    
820                    try {
821                            DLStoreUtil.deleteFile(
822                                    dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
823                                    dlFileEntry.getName());
824                    }
825                    catch (Exception e) {
826                            if (_log.isWarnEnabled()) {
827                                    _log.warn(e, e);
828                            }
829                    }
830    
831                    return dlFileEntry;
832            }
833    
834            @Indexable(type = IndexableType.DELETE)
835            @Override
836            public DLFileEntry deleteFileEntry(long fileEntryId)
837                    throws PortalException {
838    
839                    DLFileEntry dlFileEntry = getFileEntry(fileEntryId);
840    
841                    return dlFileEntryLocalService.deleteFileEntry(dlFileEntry);
842            }
843    
844            @Indexable(type = IndexableType.DELETE)
845            @Override
846            public DLFileEntry deleteFileEntry(long userId, long fileEntryId)
847                    throws PortalException {
848    
849                    if (!hasFileEntryLock(userId, fileEntryId)) {
850                            lockFileEntry(userId, fileEntryId);
851                    }
852    
853                    try {
854                            return dlFileEntryLocalService.deleteFileEntry(fileEntryId);
855                    }
856                    finally {
857                            unlockFileEntry(fileEntryId);
858                    }
859            }
860    
861            @Indexable(type = IndexableType.REINDEX)
862            @Override
863            public DLFileEntry deleteFileVersion(
864                            long userId, long fileEntryId, String version)
865                    throws PortalException {
866    
867                    if (Validator.isNull(version)) {
868                            throw new InvalidFileVersionException("Version is null");
869                    }
870    
871                    if (version.equals(DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION)) {
872                            throw new InvalidFileVersionException(
873                                    "Unable to delete a private working copy file version");
874                    }
875    
876                    if (!hasFileEntryLock(userId, fileEntryId)) {
877                            lockFileEntry(userId, fileEntryId);
878                    }
879    
880                    boolean latestVersion = false;
881    
882                    DLFileEntry dlFileEntry = null;
883    
884                    try {
885                            DLFileVersion dlFileVersion = dlFileVersionPersistence.findByF_V(
886                                    fileEntryId, version);
887    
888                            if (!dlFileVersion.isApproved()) {
889                                    throw new InvalidFileVersionException(
890                                            "Cannot delete an unapproved file version");
891                            }
892                            else {
893                                    int count = dlFileVersionPersistence.countByF_S(
894                                            fileEntryId, WorkflowConstants.STATUS_APPROVED);
895    
896                                    if (count <= 1) {
897                                            throw new InvalidFileVersionException(
898                                                    "Cannot delete the only approved file version");
899                                    }
900                            }
901    
902                            dlFileVersionPersistence.remove(dlFileVersion);
903    
904                            expandoRowLocalService.deleteRows(dlFileVersion.getFileVersionId());
905    
906                            dlFileEntryMetadataLocalService.deleteFileVersionFileEntryMetadata(
907                                    dlFileVersion.getFileVersionId());
908    
909                            workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
910                                    dlFileVersion.getCompanyId(), dlFileVersion.getGroupId(),
911                                    DLFileEntryConstants.getClassName(),
912                                    dlFileVersion.getFileVersionId());
913    
914                            dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(fileEntryId);
915    
916                            latestVersion = version.equals(dlFileEntry.getVersion());
917    
918                            if (latestVersion) {
919                                    DLFileVersion dlLatestFileVersion =
920                                            dlFileVersionLocalService.fetchLatestFileVersion(
921                                                    dlFileEntry.getFileEntryId(), true);
922    
923                                    if (dlLatestFileVersion != null) {
924                                            dlLatestFileVersion.setModifiedDate(new Date());
925                                            dlLatestFileVersion.setStatusDate(new Date());
926    
927                                            dlFileVersionPersistence.update(dlLatestFileVersion);
928    
929                                            dlFileEntry.setModifiedDate(new Date());
930                                            dlFileEntry.setFileName(dlLatestFileVersion.getFileName());
931                                            dlFileEntry.setExtension(
932                                                    dlLatestFileVersion.getExtension());
933                                            dlFileEntry.setMimeType(dlLatestFileVersion.getMimeType());
934                                            dlFileEntry.setTitle(dlLatestFileVersion.getTitle());
935                                            dlFileEntry.setDescription(
936                                                    dlLatestFileVersion.getDescription());
937                                            dlFileEntry.setExtraSettings(
938                                                    dlLatestFileVersion.getExtraSettings());
939                                            dlFileEntry.setFileEntryTypeId(
940                                                    dlLatestFileVersion.getFileEntryTypeId());
941                                            dlFileEntry.setVersion(dlLatestFileVersion.getVersion());
942                                            dlFileEntry.setSize(dlLatestFileVersion.getSize());
943    
944                                            dlFileEntry = dlFileEntryPersistence.update(dlFileEntry);
945                                    }
946                            }
947    
948                            DLStoreUtil.deleteFile(
949                                    dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
950                                    dlFileEntry.getName(), version);
951                    }
952                    finally {
953                            unlockFileEntry(fileEntryId);
954                    }
955    
956                    if (latestVersion) {
957                            return dlFileEntry;
958                    }
959    
960                    return null;
961            }
962    
963            @Override
964            public void deleteRepositoryFileEntries(long repositoryId, long folderId)
965                    throws PortalException {
966    
967                    deleteRepositoryFileEntries(repositoryId, folderId, true);
968            }
969    
970            @Override
971            public void deleteRepositoryFileEntries(
972                            final long repositoryId, final long folderId,
973                            final boolean includeTrashedEntries)
974                    throws PortalException {
975    
976                    final RepositoryEventTrigger repositoryEventTrigger =
977                            RepositoryUtil.getRepositoryEventTrigger(repositoryId);
978    
979                    int total = dlFileEntryPersistence.countByR_F(repositoryId, folderId);
980    
981                    final IntervalActionProcessor<Void> intervalActionProcessor =
982                            new IntervalActionProcessor<>(total);
983    
984                    intervalActionProcessor.setPerformIntervalActionMethod(
985                            new IntervalActionProcessor.PerformIntervalActionMethod<Void>() {
986    
987                                    @Override
988                                    public Void performIntervalAction(int start, int end)
989                                            throws PortalException {
990    
991                                            List<DLFileEntry> dlFileEntries =
992                                                    dlFileEntryPersistence.findByR_F(
993                                                            repositoryId, folderId, start, end);
994    
995                                            for (DLFileEntry dlFileEntry : dlFileEntries) {
996                                                    if (includeTrashedEntries ||
997                                                            !dlFileEntry.isInTrashExplicitly()) {
998    
999                                                            repositoryEventTrigger.trigger(
1000                                                                    RepositoryEventType.Delete.class,
1001                                                                    FileEntry.class,
1002                                                                    new LiferayFileEntry(dlFileEntry));
1003    
1004                                                            dlFileEntryLocalService.deleteFileEntry(
1005                                                                    dlFileEntry);
1006                                                    }
1007                                                    else {
1008                                                            intervalActionProcessor.incrementStart();
1009                                                    }
1010                                            }
1011    
1012                                            return null;
1013                                    }
1014    
1015                            });
1016    
1017                    intervalActionProcessor.performIntervalActions();
1018            }
1019    
1020            @Override
1021            public DLFileEntry fetchFileEntry(
1022                    long groupId, long folderId, String title) {
1023    
1024                    return dlFileEntryPersistence.fetchByG_F_T(groupId, folderId, title);
1025            }
1026    
1027            @Override
1028            public DLFileEntry fetchFileEntryByAnyImageId(long imageId) {
1029                    return dlFileEntryFinder.fetchByAnyImageId(imageId);
1030            }
1031    
1032            @Override
1033            public DLFileEntry fetchFileEntryByFileName(
1034                    long groupId, long folderId, String fileName) {
1035    
1036                    return dlFileEntryPersistence.fetchByG_F_FN(
1037                            groupId, folderId, fileName);
1038            }
1039    
1040            @Override
1041            public DLFileEntry fetchFileEntryByName(
1042                    long groupId, long folderId, String name) {
1043    
1044                    return dlFileEntryPersistence.fetchByG_F_N(groupId, folderId, name);
1045            }
1046    
1047            @Override
1048            public List<DLFileEntry> getDDMStructureFileEntries(
1049                    long groupId, long[] ddmStructureIds) {
1050    
1051                    return dlFileEntryFinder.findByDDMStructureIds(
1052                            groupId, ddmStructureIds, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
1053            }
1054    
1055            @Override
1056            public List<DLFileEntry> getDDMStructureFileEntries(
1057                    long[] ddmStructureIds) {
1058    
1059                    return dlFileEntryFinder.findByDDMStructureIds(
1060                            ddmStructureIds, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
1061            }
1062    
1063            @Override
1064            public List<DLFileEntry> getExtraSettingsFileEntries(int start, int end) {
1065                    return dlFileEntryFinder.findByExtraSettings(start, end);
1066            }
1067    
1068            @Override
1069            public int getExtraSettingsFileEntriesCount() {
1070                    return dlFileEntryFinder.countByExtraSettings();
1071            }
1072    
1073            /**
1074             * @deprecated As of 7.0.0, replaced by {@link #getFile(long, String,
1075             *             boolean)}
1076             */
1077            @Deprecated
1078            @Override
1079            public File getFile(
1080                            long userId, long fileEntryId, String version,
1081                            boolean incrementCounter)
1082                    throws PortalException {
1083    
1084                    return getFile(fileEntryId, version, incrementCounter, 1);
1085            }
1086    
1087            /**
1088             * @deprecated As of 7.0.0, replaced by {@link #getFile(long, String,
1089             *             boolean, int)}
1090             */
1091            @Deprecated
1092            @Override
1093            public File getFile(
1094                            long userId, long fileEntryId, String version,
1095                            boolean incrementCounter, int increment)
1096                    throws PortalException {
1097    
1098                    return getFile(fileEntryId, version, incrementCounter, increment);
1099            }
1100    
1101            @Override
1102            public File getFile(
1103                            long fileEntryId, String version, boolean incrementCounter)
1104                    throws PortalException {
1105    
1106                    return getFile(fileEntryId, version, incrementCounter, 1);
1107            }
1108    
1109            @Override
1110            public File getFile(
1111                            long fileEntryId, String version, boolean incrementCounter,
1112                            int increment)
1113                    throws PortalException {
1114    
1115                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
1116                            fileEntryId);
1117    
1118                    if (incrementCounter) {
1119                            dlFileEntryLocalService.incrementViewCounter(
1120                                    dlFileEntry, increment);
1121                    }
1122    
1123                    return DLStoreUtil.getFile(
1124                            dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
1125                            dlFileEntry.getName(), version);
1126            }
1127    
1128            /**
1129             * @deprecated As of 7.0.0, replaced by {@link #getFileAsStream(long,
1130             *             String)}
1131             */
1132            @Deprecated
1133            @Override
1134            public InputStream getFileAsStream(
1135                            long userId, long fileEntryId, String version)
1136                    throws PortalException {
1137    
1138                    return getFileAsStream(fileEntryId, version, true, 1);
1139            }
1140    
1141            /**
1142             * @deprecated As of 7.0.0, replaced by {@link #getFileAsStream(long,
1143             *             String, boolean)}
1144             */
1145            @Deprecated
1146            @Override
1147            public InputStream getFileAsStream(
1148                            long userId, long fileEntryId, String version,
1149                            boolean incrementCounter)
1150                    throws PortalException {
1151    
1152                    return getFileAsStream(fileEntryId, version, incrementCounter, 1);
1153            }
1154    
1155            /**
1156             * @deprecated As of 7.0.0, replaced by {@link #getFileAsStream(long,
1157             *             String, boolean, int)}
1158             */
1159            @Deprecated
1160            @Override
1161            public InputStream getFileAsStream(
1162                            long userId, long fileEntryId, String version,
1163                            boolean incrementCounter, int increment)
1164                    throws PortalException {
1165    
1166                    return getFileAsStream(
1167                            fileEntryId, version, incrementCounter, increment);
1168            }
1169    
1170            @Override
1171            public InputStream getFileAsStream(long fileEntryId, String version)
1172                    throws PortalException {
1173    
1174                    return getFileAsStream(fileEntryId, version, true, 1);
1175            }
1176    
1177            @Override
1178            public InputStream getFileAsStream(
1179                            long fileEntryId, String version, boolean incrementCounter)
1180                    throws PortalException {
1181    
1182                    return getFileAsStream(fileEntryId, version, incrementCounter, 1);
1183            }
1184    
1185            @Override
1186            public InputStream getFileAsStream(
1187                            long fileEntryId, String version, boolean incrementCounter,
1188                            int increment)
1189                    throws PortalException {
1190    
1191                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
1192                            fileEntryId);
1193    
1194                    if (incrementCounter) {
1195                            dlFileEntryLocalService.incrementViewCounter(
1196                                    dlFileEntry, increment);
1197                    }
1198    
1199                    return DLStoreUtil.getFileAsStream(
1200                            dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
1201                            dlFileEntry.getName(), version);
1202            }
1203    
1204            @Override
1205            public List<DLFileEntry> getFileEntries(int start, int end) {
1206                    return dlFileEntryPersistence.findAll(start, end);
1207            }
1208    
1209            @Override
1210            public List<DLFileEntry> getFileEntries(long groupId, long folderId) {
1211                    return dlFileEntryPersistence.findByG_F(groupId, folderId);
1212            }
1213    
1214            @Override
1215            public List<DLFileEntry> getFileEntries(
1216                    long groupId, long folderId, int status, int start, int end,
1217                    OrderByComparator<DLFileEntry> obc) {
1218    
1219                    List<Long> folderIds = new ArrayList<>();
1220    
1221                    folderIds.add(folderId);
1222    
1223                    QueryDefinition<DLFileEntry> queryDefinition = new QueryDefinition<>(
1224                            status, false, start, end, obc);
1225    
1226                    return dlFileEntryFinder.findByG_F(groupId, folderIds, queryDefinition);
1227            }
1228    
1229            @Override
1230            public List<DLFileEntry> getFileEntries(
1231                    long groupId, long folderId, int start, int end,
1232                    OrderByComparator<DLFileEntry> obc) {
1233    
1234                    return dlFileEntryPersistence.findByG_F(
1235                            groupId, folderId, start, end, obc);
1236            }
1237    
1238            @Override
1239            public List<DLFileEntry> getFileEntries(
1240                            long groupId, long userId, List<Long> repositoryIds,
1241                            List<Long> folderIds, String[] mimeTypes,
1242                            QueryDefinition<DLFileEntry> queryDefinition)
1243                    throws Exception {
1244    
1245                    return dlFileEntryFinder.findByG_U_R_F_M(
1246                            groupId, userId, repositoryIds, folderIds, mimeTypes,
1247                            queryDefinition);
1248            }
1249    
1250            @Override
1251            public List<DLFileEntry> getFileEntries(
1252                            long groupId, long userId, List<Long> folderIds, String[] mimeTypes,
1253                            QueryDefinition<DLFileEntry> queryDefinition)
1254                    throws Exception {
1255    
1256                    return dlFileEntryFinder.findByG_U_F_M(
1257                            groupId, userId, folderIds, mimeTypes, queryDefinition);
1258            }
1259    
1260            @Override
1261            public List<DLFileEntry> getFileEntries(long folderId, String name) {
1262                    return dlFileEntryPersistence.findByF_N(folderId, name);
1263            }
1264    
1265            @Override
1266            public int getFileEntriesCount() {
1267                    return dlFileEntryPersistence.countAll();
1268            }
1269    
1270            /**
1271             * @deprecated As of 7.0.0, with no direct replacement
1272             */
1273            @Deprecated
1274            @Override
1275            public int getFileEntriesCount(
1276                    long groupId, DateRange dateRange, long repositoryId,
1277                    QueryDefinition<DLFileEntry> queryDefinition) {
1278    
1279                    return 0;
1280            }
1281    
1282            @Override
1283            public int getFileEntriesCount(long groupId, long folderId) {
1284                    return dlFileEntryPersistence.countByG_F(groupId, folderId);
1285            }
1286    
1287            @Override
1288            public int getFileEntriesCount(long groupId, long folderId, int status) {
1289                    List<Long> folderIds = new ArrayList<>();
1290    
1291                    folderIds.add(folderId);
1292    
1293                    return dlFileEntryFinder.countByG_F(
1294                            groupId, folderIds, new QueryDefinition<DLFileEntry>(status));
1295            }
1296    
1297            @Override
1298            public int getFileEntriesCount(
1299                            long groupId, long userId, List<Long> repositoryIds,
1300                            List<Long> folderIds, String[] mimeTypes,
1301                            QueryDefinition<DLFileEntry> queryDefinition)
1302                    throws Exception {
1303    
1304                    return dlFileEntryFinder.countByG_U_R_F_M(
1305                            groupId, userId, repositoryIds, folderIds, mimeTypes,
1306                            queryDefinition);
1307            }
1308    
1309            @Override
1310            public int getFileEntriesCount(
1311                            long groupId, long userId, List<Long> folderIds, String[] mimeTypes,
1312                            QueryDefinition<DLFileEntry> queryDefinition)
1313                    throws Exception {
1314    
1315                    return dlFileEntryFinder.countByG_U_F_M(
1316                            groupId, userId, folderIds, mimeTypes, queryDefinition);
1317            }
1318    
1319            @Override
1320            public DLFileEntry getFileEntry(long fileEntryId) throws PortalException {
1321                    return dlFileEntryPersistence.findByPrimaryKey(fileEntryId);
1322            }
1323    
1324            @Override
1325            public DLFileEntry getFileEntry(long groupId, long folderId, String title)
1326                    throws PortalException {
1327    
1328                    DLFileEntry dlFileEntry = dlFileEntryPersistence.fetchByG_F_T(
1329                            groupId, folderId, title);
1330    
1331                    if (dlFileEntry != null) {
1332                            return dlFileEntry;
1333                    }
1334    
1335                    List<DLFileVersion> dlFileVersions =
1336                            dlFileVersionPersistence.findByG_F_T_V(
1337                                    groupId, folderId, title,
1338                                    DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION);
1339    
1340                    long userId = PrincipalThreadLocal.getUserId();
1341    
1342                    for (DLFileVersion dlFileVersion : dlFileVersions) {
1343                            if (hasFileEntryLock(userId, dlFileVersion.getFileEntryId())) {
1344                                    return dlFileVersion.getFileEntry();
1345                            }
1346                    }
1347    
1348                    StringBundler sb = new StringBundler(8);
1349    
1350                    sb.append("No DLFileEntry exists with the key {");
1351                    sb.append("groupId=");
1352                    sb.append(groupId);
1353                    sb.append(", folderId=");
1354                    sb.append(folderId);
1355                    sb.append(", title=");
1356                    sb.append(title);
1357                    sb.append(StringPool.CLOSE_CURLY_BRACE);
1358    
1359                    throw new NoSuchFileEntryException(sb.toString());
1360            }
1361    
1362            @Override
1363            public DLFileEntry getFileEntryByName(
1364                            long groupId, long folderId, String name)
1365                    throws PortalException {
1366    
1367                    return dlFileEntryPersistence.findByG_F_N(groupId, folderId, name);
1368            }
1369    
1370            @Override
1371            public DLFileEntry getFileEntryByUuidAndGroupId(String uuid, long groupId)
1372                    throws PortalException {
1373    
1374                    return dlFileEntryPersistence.findByUUID_G(uuid, groupId);
1375            }
1376    
1377            @Override
1378            public List<DLFileEntry> getGroupFileEntries(
1379                    long groupId, int start, int end) {
1380    
1381                    return getGroupFileEntries(
1382                            groupId, start, end,
1383                            new RepositoryModelModifiedDateComparator<DLFileEntry>());
1384            }
1385    
1386            @Override
1387            public List<DLFileEntry> getGroupFileEntries(
1388                    long groupId, int start, int end, OrderByComparator<DLFileEntry> obc) {
1389    
1390                    return dlFileEntryPersistence.findByGroupId(groupId, start, end, obc);
1391            }
1392    
1393            @Override
1394            public List<DLFileEntry> getGroupFileEntries(
1395                    long groupId, long userId, int start, int end) {
1396    
1397                    return getGroupFileEntries(
1398                            groupId, userId, start, end,
1399                            new RepositoryModelModifiedDateComparator<DLFileEntry>());
1400            }
1401    
1402            @Override
1403            public List<DLFileEntry> getGroupFileEntries(
1404                    long groupId, long userId, int start, int end,
1405                    OrderByComparator<DLFileEntry> obc) {
1406    
1407                    if (userId <= 0) {
1408                            return dlFileEntryPersistence.findByGroupId(
1409                                    groupId, start, end, obc);
1410                    }
1411                    else {
1412                            return dlFileEntryPersistence.findByG_U(
1413                                    groupId, userId, start, end, obc);
1414                    }
1415            }
1416    
1417            @Override
1418            public List<DLFileEntry> getGroupFileEntries(
1419                    long groupId, long userId, long rootFolderId, int start, int end,
1420                    OrderByComparator<DLFileEntry> obc) {
1421    
1422                    return getGroupFileEntries(
1423                            groupId, userId, 0, rootFolderId, start, end, obc);
1424            }
1425    
1426            @Override
1427            public List<DLFileEntry> getGroupFileEntries(
1428                    long groupId, long userId, long repositoryId, long rootFolderId,
1429                    int start, int end, OrderByComparator<DLFileEntry> obc) {
1430    
1431                    List<Long> folderIds = null;
1432    
1433                    if (repositoryId != 0) {
1434                            folderIds = dlFolderLocalService.getRepositoryFolderIds(
1435                                    repositoryId, rootFolderId);
1436                    }
1437                    else {
1438                            folderIds = dlFolderLocalService.getGroupFolderIds(
1439                                    groupId, rootFolderId);
1440                    }
1441    
1442                    if (folderIds.isEmpty()) {
1443                            return Collections.emptyList();
1444                    }
1445    
1446                    QueryDefinition<DLFileEntry> queryDefinition = new QueryDefinition<>(
1447                            WorkflowConstants.STATUS_ANY, start, end, obc);
1448    
1449                    if (repositoryId == 0) {
1450                            if (userId <= 0) {
1451                                    return dlFileEntryFinder.findByG_F(
1452                                            groupId, folderIds, queryDefinition);
1453                            }
1454                            else {
1455                                    return dlFileEntryFinder.findByG_U_F(
1456                                            groupId, userId, folderIds, queryDefinition);
1457                            }
1458                    }
1459                    else {
1460                            List<Long> repositoryIds = new ArrayList<>();
1461    
1462                            repositoryIds.add(repositoryId);
1463    
1464                            if (userId <= 0) {
1465                                    return dlFileEntryFinder.findByG_R_F(
1466                                            groupId, repositoryIds, folderIds, queryDefinition);
1467                            }
1468                            else {
1469                                    return dlFileEntryFinder.findByG_U_R_F(
1470                                            groupId, userId, repositoryIds, folderIds, queryDefinition);
1471                            }
1472                    }
1473            }
1474    
1475            @Override
1476            public int getGroupFileEntriesCount(long groupId) {
1477                    return dlFileEntryPersistence.countByGroupId(groupId);
1478            }
1479    
1480            @Override
1481            public int getGroupFileEntriesCount(long groupId, long userId) {
1482                    if (userId <= 0) {
1483                            return dlFileEntryPersistence.countByGroupId(groupId);
1484                    }
1485                    else {
1486                            return dlFileEntryPersistence.countByG_U(groupId, userId);
1487                    }
1488            }
1489    
1490            @Override
1491            public List<DLFileEntry> getMisversionedFileEntries() {
1492                    return dlFileEntryFinder.findByMisversioned();
1493            }
1494    
1495            @Override
1496            public List<DLFileEntry> getNoAssetFileEntries() {
1497                    return dlFileEntryFinder.findByNoAssets();
1498            }
1499    
1500            @Override
1501            public List<DLFileEntry> getOrphanedFileEntries() {
1502                    return dlFileEntryFinder.findByOrphanedFileEntries();
1503            }
1504    
1505            @Override
1506            public List<DLFileEntry> getRepositoryFileEntries(
1507                    long repositoryId, int start, int end) {
1508    
1509                    return dlFileEntryPersistence.findByRepositoryId(
1510                            repositoryId, start, end);
1511            }
1512    
1513            @Override
1514            public int getRepositoryFileEntriesCount(long repositoryId) {
1515                    return dlFileEntryPersistence.countByRepositoryId(repositoryId);
1516            }
1517    
1518            @Override
1519            public String getUniqueTitle(
1520                            long groupId, long folderId, long fileEntryId, String title,
1521                            String extension)
1522                    throws PortalException {
1523    
1524                    String uniqueTitle = title;
1525    
1526                    for (int i = 1;; i++) {
1527                            String uniqueFileName = DLUtil.getSanitizedFileName(
1528                                    uniqueTitle, extension);
1529    
1530                            try {
1531                                    validateFile(
1532                                            groupId, folderId, fileEntryId, uniqueFileName,
1533                                            uniqueTitle);
1534    
1535                                    return uniqueTitle;
1536                            }
1537                            catch (PortalException pe) {
1538                                    if (!(pe instanceof DuplicateFolderNameException) &&
1539                                             !(pe instanceof DuplicateFileEntryException)) {
1540    
1541                                            throw pe;
1542                                    }
1543                            }
1544    
1545                            uniqueTitle = FileUtil.appendParentheticalSuffix(
1546                                    title, String.valueOf(i));
1547                    }
1548            }
1549    
1550            @Override
1551            public boolean hasExtraSettings() {
1552                    if (dlFileEntryFinder.countByExtraSettings() > 0) {
1553                            return true;
1554                    }
1555                    else {
1556                            return false;
1557                    }
1558            }
1559    
1560            @Override
1561            public boolean hasFileEntryLock(long userId, long fileEntryId)
1562                    throws PortalException {
1563    
1564                    DLFileEntry dlFileEntry = getFileEntry(fileEntryId);
1565    
1566                    long folderId = dlFileEntry.getFolderId();
1567    
1568                    boolean hasLock = LockManagerUtil.hasLock(
1569                            userId, DLFileEntry.class.getName(), fileEntryId);
1570    
1571                    if (!hasLock &&
1572                            (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID)) {
1573    
1574                            hasLock = dlFolderLocalService.hasInheritableLock(folderId);
1575                    }
1576    
1577                    return hasLock;
1578            }
1579    
1580            @BufferedIncrement(
1581                    configuration = "DLFileEntry", incrementClass = NumberIncrement.class
1582            )
1583            @Override
1584            public void incrementViewCounter(DLFileEntry dlFileEntry, int increment) {
1585                    if (ExportImportThreadLocal.isImportInProcess()) {
1586                            return;
1587                    }
1588    
1589                    dlFileEntry.setModifiedDate(dlFileEntry.getModifiedDate());
1590                    dlFileEntry.setReadCount(dlFileEntry.getReadCount() + increment);
1591    
1592                    dlFileEntryPersistence.update(dlFileEntry);
1593            }
1594    
1595            @Override
1596            public boolean isFileEntryCheckedOut(long fileEntryId)
1597                    throws PortalException {
1598    
1599                    DLFileVersion dlFileVersion =
1600                            dlFileVersionLocalService.getLatestFileVersion(fileEntryId, false);
1601    
1602                    String version = dlFileVersion.getVersion();
1603    
1604                    if (version.equals(DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION)) {
1605                            return true;
1606                    }
1607                    else {
1608                            return false;
1609                    }
1610            }
1611    
1612            @Override
1613            public boolean isKeepFileVersionLabel(
1614                            long fileEntryId, ServiceContext serviceContext)
1615                    throws PortalException {
1616    
1617                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
1618                            fileEntryId);
1619    
1620                    DLFileVersion lastDLFileVersion =
1621                            dlFileVersionLocalService.getFileVersion(
1622                                    dlFileEntry.getFileEntryId(), dlFileEntry.getVersion());
1623    
1624                    DLFileVersion latestDLFileVersion =
1625                            dlFileVersionLocalService.getLatestFileVersion(fileEntryId, false);
1626    
1627                    return isKeepFileVersionLabel(
1628                            dlFileEntry, lastDLFileVersion, latestDLFileVersion,
1629                            serviceContext);
1630            }
1631    
1632            @Override
1633            public Lock lockFileEntry(long userId, long fileEntryId)
1634                    throws PortalException {
1635    
1636                    if (hasFileEntryLock(userId, fileEntryId)) {
1637                            return LockManagerUtil.getLock(
1638                                    DLFileEntry.class.getName(), fileEntryId);
1639                    }
1640    
1641                    return LockManagerUtil.lock(
1642                            userId, DLFileEntry.class.getName(), fileEntryId, null, false,
1643                            DLFileEntryImpl.LOCK_EXPIRATION_TIME);
1644            }
1645    
1646            @Indexable(type = IndexableType.REINDEX)
1647            @Override
1648            public DLFileEntry moveFileEntry(
1649                            long userId, long fileEntryId, long newFolderId,
1650                            ServiceContext serviceContext)
1651                    throws PortalException {
1652    
1653                    if (!hasFileEntryLock(userId, fileEntryId)) {
1654                            lockFileEntry(userId, fileEntryId);
1655                    }
1656    
1657                    try {
1658                            DLFileEntry dlFileEntry = moveFileEntryImpl(
1659                                    userId, fileEntryId, newFolderId, serviceContext);
1660    
1661                            return dlFileEntryTypeLocalService.updateFileEntryFileEntryType(
1662                                    dlFileEntry, serviceContext);
1663                    }
1664                    finally {
1665                            if (!isFileEntryCheckedOut(fileEntryId)) {
1666                                    unlockFileEntry(fileEntryId);
1667                            }
1668                    }
1669            }
1670    
1671            @Override
1672            public void rebuildTree(long companyId) throws PortalException {
1673                    dlFolderLocalService.rebuildTree(companyId);
1674            }
1675    
1676            @Override
1677            public void revertFileEntry(
1678                            long userId, long fileEntryId, String version,
1679                            ServiceContext serviceContext)
1680                    throws PortalException {
1681    
1682                    if (Validator.isNull(version)) {
1683                            throw new InvalidFileVersionException("Version is null");
1684                    }
1685    
1686                    if (version.equals(DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION)) {
1687                            throw new InvalidFileVersionException(
1688                                    "Unable to revert a private working copy file version");
1689                    }
1690    
1691                    DLFileVersion dlFileVersion = dlFileVersionLocalService.getFileVersion(
1692                            fileEntryId, version);
1693    
1694                    if (!dlFileVersion.isApproved()) {
1695                            throw new InvalidFileVersionException(
1696                                    "Unable to revert from an unapproved file version");
1697                    }
1698    
1699                    DLFileVersion latestDLFileVersion =
1700                            dlFileVersionLocalService.getLatestFileVersion(fileEntryId, false);
1701    
1702                    if (version.equals(latestDLFileVersion.getVersion())) {
1703                            throw new InvalidFileVersionException(
1704                                    "Unable to revert from the latest file version");
1705                    }
1706    
1707                    String sourceFileName = dlFileVersion.getTitle();
1708                    String extension = dlFileVersion.getExtension();
1709                    String mimeType = dlFileVersion.getMimeType();
1710                    String title = dlFileVersion.getTitle();
1711                    String description = dlFileVersion.getDescription();
1712                    String changeLog = LanguageUtil.format(
1713                            serviceContext.getLocale(), "reverted-to-x", version, false);
1714                    boolean majorVersion = true;
1715                    String extraSettings = dlFileVersion.getExtraSettings();
1716                    long fileEntryTypeId = dlFileVersion.getFileEntryTypeId();
1717                    Map<String, DDMFormValues> ddmFormValuesMap = null;
1718                    InputStream is = getFileAsStream(fileEntryId, version, false);
1719                    long size = dlFileVersion.getSize();
1720    
1721                    serviceContext.setCommand(Constants.REVERT);
1722    
1723                    DLFileEntry dlFileEntry = updateFileEntry(
1724                            userId, fileEntryId, sourceFileName, extension, mimeType, title,
1725                            description, changeLog, majorVersion, extraSettings,
1726                            fileEntryTypeId, ddmFormValuesMap, null, is, size, serviceContext);
1727    
1728                    DLFileVersion newDlFileVersion =
1729                            dlFileVersionLocalService.getFileVersion(
1730                                    fileEntryId, dlFileEntry.getVersion());
1731    
1732                    copyFileEntryMetadata(
1733                            dlFileVersion.getCompanyId(), dlFileVersion.getFileEntryTypeId(),
1734                            fileEntryId, dlFileVersion.getFileVersionId(),
1735                            newDlFileVersion.getFileVersionId(), serviceContext);
1736            }
1737    
1738            @Override
1739            public Hits search(
1740                            long groupId, long userId, long creatorUserId, int status,
1741                            int start, int end)
1742                    throws PortalException {
1743    
1744                    return search(
1745                            groupId, userId, creatorUserId,
1746                            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, null, status, start,
1747                            end);
1748            }
1749    
1750            @Override
1751            public Hits search(
1752                            long groupId, long userId, long creatorUserId, long folderId,
1753                            String[] mimeTypes, int status, int start, int end)
1754                    throws PortalException {
1755    
1756                    Indexer<DLFileEntry> indexer = IndexerRegistryUtil.getIndexer(
1757                            DLFileEntryConstants.getClassName());
1758    
1759                    SearchContext searchContext = new SearchContext();
1760    
1761                    searchContext.setAttribute(Field.STATUS, status);
1762    
1763                    if (creatorUserId > 0) {
1764                            searchContext.setAttribute(
1765                                    Field.USER_ID, String.valueOf(creatorUserId));
1766                    }
1767    
1768                    if (ArrayUtil.isNotEmpty(mimeTypes)) {
1769                            searchContext.setAttribute("mimeTypes", mimeTypes);
1770                    }
1771    
1772                    searchContext.setAttribute("paginationType", "none");
1773    
1774                    Group group = groupLocalService.getGroup(groupId);
1775    
1776                    searchContext.setCompanyId(group.getCompanyId());
1777    
1778                    searchContext.setEnd(end);
1779                    searchContext.setFolderIds(new long[] {folderId});
1780                    searchContext.setGroupIds(new long[] {groupId});
1781                    searchContext.setSorts(new Sort(Field.MODIFIED_DATE, true));
1782                    searchContext.setStart(start);
1783                    searchContext.setUserId(userId);
1784    
1785                    return indexer.search(searchContext);
1786            }
1787    
1788            @Override
1789            public void setTreePaths(
1790                            final long folderId, final String treePath, final boolean reindex)
1791                    throws PortalException {
1792    
1793                    if (treePath == null) {
1794                            throw new IllegalArgumentException("Tree path is null");
1795                    }
1796    
1797                    final IndexableActionableDynamicQuery indexableActionableDynamicQuery =
1798                            getIndexableActionableDynamicQuery();
1799    
1800                    indexableActionableDynamicQuery.setAddCriteriaMethod(
1801                            new ActionableDynamicQuery.AddCriteriaMethod() {
1802    
1803                                    @Override
1804                                    public void addCriteria(DynamicQuery dynamicQuery) {
1805                                            Property folderIdProperty = PropertyFactoryUtil.forName(
1806                                                    "folderId");
1807    
1808                                            dynamicQuery.add(folderIdProperty.eq(folderId));
1809    
1810                                            Property treePathProperty = PropertyFactoryUtil.forName(
1811                                                    "treePath");
1812    
1813                                            dynamicQuery.add(
1814                                                    RestrictionsFactoryUtil.or(
1815                                                            treePathProperty.isNull(),
1816                                                            treePathProperty.ne(treePath)));
1817                                    }
1818    
1819                            });
1820    
1821                    final Indexer<DLFileEntry> indexer = IndexerRegistryUtil.getIndexer(
1822                            DLFileEntry.class.getName());
1823    
1824                    indexableActionableDynamicQuery.setPerformActionMethod(
1825                            new ActionableDynamicQuery.PerformActionMethod<DLFileEntry>() {
1826    
1827                                    @Override
1828                                    public void performAction(DLFileEntry dlFileEntry)
1829                                            throws PortalException {
1830    
1831                                            dlFileEntry.setTreePath(treePath);
1832    
1833                                            updateDLFileEntry(dlFileEntry);
1834    
1835                                            if (!reindex) {
1836                                                    return;
1837                                            }
1838    
1839                                            Document document = indexer.getDocument(dlFileEntry);
1840    
1841                                            indexableActionableDynamicQuery.addDocuments(document);
1842                                    }
1843    
1844                            });
1845    
1846                    indexableActionableDynamicQuery.performActions();
1847            }
1848    
1849            @Override
1850            public void unlockFileEntry(long fileEntryId) {
1851                    LockManagerUtil.unlock(DLFileEntry.class.getName(), fileEntryId);
1852            }
1853    
1854            @Override
1855            public DLFileEntry updateFileEntry(
1856                            long userId, long fileEntryId, String sourceFileName,
1857                            String mimeType, String title, String description, String changeLog,
1858                            boolean majorVersion, long fileEntryTypeId,
1859                            Map<String, DDMFormValues> ddmFormValuesMap, File file,
1860                            InputStream is, long size, ServiceContext serviceContext)
1861                    throws PortalException {
1862    
1863                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
1864                            fileEntryId);
1865    
1866                    String extension = DLAppUtil.getExtension(title, sourceFileName);
1867    
1868                    String extraSettings = StringPool.BLANK;
1869    
1870                    if (fileEntryTypeId == -1) {
1871                            fileEntryTypeId = dlFileEntry.getFileEntryTypeId();
1872                    }
1873    
1874                    validateFileEntryTypeId(
1875                            PortalUtil.getCurrentAndAncestorSiteGroupIds(
1876                                    dlFileEntry.getGroupId()),
1877                            dlFileEntry.getFolderId(), fileEntryTypeId);
1878    
1879                    return updateFileEntry(
1880                            userId, fileEntryId, sourceFileName, extension, mimeType, title,
1881                            description, changeLog, majorVersion, extraSettings,
1882                            fileEntryTypeId, ddmFormValuesMap, file, is, size, serviceContext);
1883            }
1884    
1885            @Override
1886            public DLFileEntry updateFileEntryType(
1887                            long userId, long fileEntryId, long fileEntryTypeId,
1888                            ServiceContext serviceContext)
1889                    throws PortalException {
1890    
1891                    User user = userPersistence.findByPrimaryKey(userId);
1892    
1893                    DLFileEntry dlFileEntry = dlFileEntryLocalService.getFileEntry(
1894                            fileEntryId);
1895    
1896                    dlFileEntry.setFileEntryTypeId(fileEntryTypeId);
1897    
1898                    dlFileEntryLocalService.updateDLFileEntry(dlFileEntry);
1899    
1900                    DLFileVersion dlFileVersion =
1901                            dlFileVersionLocalService.getLatestFileVersion(
1902                                    fileEntryId, !dlFileEntry.isCheckedOut());
1903    
1904                    dlFileVersion.setUserId(user.getUserId());
1905                    dlFileVersion.setUserName(user.getFullName());
1906                    dlFileVersion.setFileEntryTypeId(fileEntryTypeId);
1907    
1908                    dlFileVersionLocalService.updateDLFileVersion(dlFileVersion);
1909    
1910                    return dlFileEntry;
1911            }
1912    
1913            @Override
1914            public void updateSmallImage(long smallImageId, long largeImageId)
1915                    throws PortalException {
1916    
1917                    try {
1918                            RenderedImage renderedImage = null;
1919    
1920                            Image largeImage = imageLocalService.getImage(largeImageId);
1921    
1922                            byte[] bytes = largeImage.getTextObj();
1923                            String contentType = largeImage.getType();
1924    
1925                            if (bytes != null) {
1926                                    ImageBag imageBag = ImageToolUtil.read(bytes);
1927    
1928                                    renderedImage = imageBag.getRenderedImage();
1929    
1930                                    //validate(bytes);
1931                            }
1932    
1933                            if (renderedImage != null) {
1934                                    int height = PrefsPropsUtil.getInteger(
1935                                            PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_HEIGHT);
1936                                    int width = PrefsPropsUtil.getInteger(
1937                                            PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_WIDTH);
1938    
1939                                    RenderedImage thumbnailRenderedImage = ImageToolUtil.scale(
1940                                            renderedImage, height, width);
1941    
1942                                    imageLocalService.updateImage(
1943                                            smallImageId,
1944                                            ImageToolUtil.getBytes(
1945                                                    thumbnailRenderedImage, contentType));
1946                            }
1947                    }
1948                    catch (IOException ioe) {
1949                            throw new ImageSizeException(ioe);
1950                    }
1951            }
1952    
1953            @Override
1954            public DLFileEntry updateStatus(
1955                            long userId, long fileVersionId, int status,
1956                            ServiceContext serviceContext,
1957                            Map<String, Serializable> workflowContext)
1958                    throws PortalException {
1959    
1960                    // File version
1961    
1962                    User user = userPersistence.findByPrimaryKey(userId);
1963    
1964                    DLFileVersion dlFileVersion = dlFileVersionPersistence.findByPrimaryKey(
1965                            fileVersionId);
1966    
1967                    int oldStatus = dlFileVersion.getStatus();
1968    
1969                    dlFileVersion.setStatus(status);
1970                    dlFileVersion.setStatusByUserId(user.getUserId());
1971                    dlFileVersion.setStatusByUserName(user.getFullName());
1972                    dlFileVersion.setStatusDate(new Date());
1973    
1974                    dlFileVersionPersistence.update(dlFileVersion);
1975    
1976                    // File entry
1977    
1978                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
1979                            dlFileVersion.getFileEntryId());
1980    
1981                    if (status == WorkflowConstants.STATUS_APPROVED) {
1982                            if (DLUtil.compareVersions(
1983                                            dlFileEntry.getVersion(),
1984                                            dlFileVersion.getVersion()) <= 0) {
1985    
1986                                    dlFileEntry.setFileName(dlFileVersion.getFileName());
1987                                    dlFileEntry.setExtension(dlFileVersion.getExtension());
1988                                    dlFileEntry.setMimeType(dlFileVersion.getMimeType());
1989                                    dlFileEntry.setTitle(dlFileVersion.getTitle());
1990                                    dlFileEntry.setDescription(dlFileVersion.getDescription());
1991                                    dlFileEntry.setExtraSettings(dlFileVersion.getExtraSettings());
1992                                    dlFileEntry.setFileEntryTypeId(
1993                                            dlFileVersion.getFileEntryTypeId());
1994                                    dlFileEntry.setVersion(dlFileVersion.getVersion());
1995                                    dlFileEntry.setModifiedDate(dlFileVersion.getCreateDate());
1996                                    dlFileEntry.setSize(dlFileVersion.getSize());
1997    
1998                                    dlFileEntryPersistence.update(dlFileEntry);
1999                            }
2000                    }
2001                    else {
2002    
2003                            // File entry
2004    
2005                            if ((status != WorkflowConstants.STATUS_IN_TRASH) &&
2006                                    Validator.equals(
2007                                            dlFileEntry.getVersion(), dlFileVersion.getVersion())) {
2008    
2009                                    String newVersion = DLFileEntryConstants.VERSION_DEFAULT;
2010    
2011                                    List<DLFileVersion> approvedFileVersions =
2012                                            dlFileVersionPersistence.findByF_S(
2013                                                    dlFileEntry.getFileEntryId(),
2014                                                    WorkflowConstants.STATUS_APPROVED);
2015    
2016                                    if (!approvedFileVersions.isEmpty()) {
2017                                            newVersion = approvedFileVersions.get(0).getVersion();
2018                                    }
2019    
2020                                    dlFileEntry.setVersion(newVersion);
2021    
2022                                    dlFileEntryPersistence.update(dlFileEntry);
2023                            }
2024    
2025                            // Indexer
2026    
2027                            if (Validator.equals(
2028                                            dlFileVersion.getVersion(),
2029                                            DLFileEntryConstants.VERSION_DEFAULT)) {
2030    
2031                                    Indexer<DLFileEntry> indexer =
2032                                            IndexerRegistryUtil.nullSafeGetIndexer(DLFileEntry.class);
2033    
2034                                    indexer.delete(dlFileEntry);
2035                            }
2036                    }
2037    
2038                    // App helper
2039    
2040                    dlAppHelperLocalService.updateStatus(
2041                            userId, new LiferayFileEntry(dlFileEntry),
2042                            new LiferayFileVersion(dlFileVersion), oldStatus, status,
2043                            serviceContext, workflowContext);
2044    
2045                    if (PropsValues.DL_FILE_ENTRY_COMMENTS_ENABLED) {
2046                            if (status == WorkflowConstants.STATUS_IN_TRASH) {
2047                                    CommentManagerUtil.moveDiscussionToTrash(
2048                                            DLFileEntry.class.getName(), dlFileEntry.getFileEntryId());
2049                            }
2050                            else if (oldStatus == WorkflowConstants.STATUS_IN_TRASH) {
2051                                    CommentManagerUtil.restoreDiscussionFromTrash(
2052                                            DLFileEntry.class.getName(), dlFileEntry.getFileEntryId());
2053                            }
2054                    }
2055    
2056                    // Indexer
2057    
2058                    if (((status == WorkflowConstants.STATUS_APPROVED) ||
2059                             (status == WorkflowConstants.STATUS_IN_TRASH) ||
2060                             (oldStatus == WorkflowConstants.STATUS_IN_TRASH)) &&
2061                            ((serviceContext == null) || serviceContext.isIndexingEnabled())) {
2062    
2063                            reindex(dlFileEntry);
2064                    }
2065    
2066                    return dlFileEntry;
2067            }
2068    
2069            @Override
2070            public void validateFile(
2071                            long groupId, long folderId, long fileEntryId, String fileName,
2072                            String title)
2073                    throws PortalException {
2074    
2075                    DLFolder dlFolder = dlFolderPersistence.fetchByG_P_N(
2076                            groupId, folderId, title);
2077    
2078                    if (dlFolder != null) {
2079                            throw new DuplicateFolderNameException(title);
2080                    }
2081    
2082                    DLFileEntry dlFileEntry = dlFileEntryPersistence.fetchByG_F_T(
2083                            groupId, folderId, title);
2084    
2085                    if ((dlFileEntry != null) &&
2086                            (dlFileEntry.getFileEntryId() != fileEntryId)) {
2087    
2088                            throw new DuplicateFileEntryException(title);
2089                    }
2090    
2091                    dlFileEntry = dlFileEntryPersistence.fetchByG_F_FN(
2092                            groupId, folderId, fileName);
2093    
2094                    if ((dlFileEntry != null) &&
2095                            (dlFileEntry.getFileEntryId() != fileEntryId)) {
2096    
2097                            throw new DuplicateFileEntryException(title);
2098                    }
2099            }
2100    
2101            @Override
2102            public boolean verifyFileEntryCheckOut(long fileEntryId, String lockUuid)
2103                    throws PortalException {
2104    
2105                    if (verifyFileEntryLock(fileEntryId, lockUuid) &&
2106                            isFileEntryCheckedOut(fileEntryId)) {
2107    
2108                            return true;
2109                    }
2110                    else {
2111                            return false;
2112                    }
2113            }
2114    
2115            @Override
2116            public boolean verifyFileEntryLock(long fileEntryId, String lockUuid)
2117                    throws PortalException {
2118    
2119                    boolean lockVerified = false;
2120    
2121                    try {
2122                            Lock lock = LockManagerUtil.getLock(
2123                                    DLFileEntry.class.getName(), fileEntryId);
2124    
2125                            if (Validator.equals(lock.getUuid(), lockUuid)) {
2126                                    lockVerified = true;
2127                            }
2128                    }
2129                    catch (PortalException pe) {
2130                            if ((pe instanceof ExpiredLockException) ||
2131                                    (pe instanceof NoSuchLockException)) {
2132    
2133                                    DLFileEntry dlFileEntry = dlFileEntryLocalService.getFileEntry(
2134                                            fileEntryId);
2135    
2136                                    lockVerified = dlFolderLocalService.verifyInheritableLock(
2137                                            dlFileEntry.getFolderId(), lockUuid);
2138                            }
2139                            else {
2140                                    throw pe;
2141                            }
2142                    }
2143    
2144                    return lockVerified;
2145            }
2146    
2147            protected DLFileVersion addFileVersion(
2148                            User user, DLFileEntry dlFileEntry, String fileName,
2149                            String extension, String mimeType, String title, String description,
2150                            String changeLog, String extraSettings, long fileEntryTypeId,
2151                            Map<String, DDMFormValues> ddmFormValuesMap, String version,
2152                            long size, int status, ServiceContext serviceContext)
2153                    throws PortalException {
2154    
2155                    long fileVersionId = counterLocalService.increment();
2156    
2157                    DLFileVersion dlFileVersion = dlFileVersionPersistence.create(
2158                            fileVersionId);
2159    
2160                    String uuid = ParamUtil.getString(
2161                            serviceContext, "fileVersionUuid", serviceContext.getUuid());
2162    
2163                    dlFileVersion.setUuid(uuid);
2164    
2165                    dlFileVersion.setGroupId(dlFileEntry.getGroupId());
2166                    dlFileVersion.setCompanyId(dlFileEntry.getCompanyId());
2167                    dlFileVersion.setUserId(user.getUserId());
2168                    dlFileVersion.setUserName(user.getFullName());
2169                    dlFileVersion.setRepositoryId(dlFileEntry.getRepositoryId());
2170                    dlFileVersion.setFolderId(dlFileEntry.getFolderId());
2171                    dlFileVersion.setFileEntryId(dlFileEntry.getFileEntryId());
2172                    dlFileVersion.setTreePath(dlFileVersion.buildTreePath());
2173                    dlFileVersion.setFileName(fileName);
2174                    dlFileVersion.setExtension(extension);
2175                    dlFileVersion.setMimeType(mimeType);
2176                    dlFileVersion.setTitle(title);
2177                    dlFileVersion.setDescription(description);
2178                    dlFileVersion.setChangeLog(changeLog);
2179                    dlFileVersion.setExtraSettings(extraSettings);
2180                    dlFileVersion.setFileEntryTypeId(fileEntryTypeId);
2181                    dlFileVersion.setVersion(version);
2182                    dlFileVersion.setSize(size);
2183                    dlFileVersion.setStatus(status);
2184                    dlFileVersion.setStatusByUserId(user.getUserId());
2185                    dlFileVersion.setStatusByUserName(user.getFullName());
2186                    dlFileVersion.setStatusDate(dlFileEntry.getModifiedDate());
2187    
2188                    ExpandoBridge oldExpandoBridge = dlFileVersion.getExpandoBridge();
2189    
2190                    DLFileVersion latestFileVersion =
2191                            dlFileVersionLocalService.fetchLatestFileVersion(
2192                                    dlFileEntry.getFileEntryId(), false);
2193    
2194                    if (latestFileVersion != null) {
2195                            oldExpandoBridge = latestFileVersion.getExpandoBridge();
2196                    }
2197    
2198                    ExpandoBridgeUtil.setExpandoBridgeAttributes(
2199                            oldExpandoBridge, dlFileVersion.getExpandoBridge(), serviceContext);
2200    
2201                    dlFileVersionPersistence.update(dlFileVersion);
2202    
2203                    if ((fileEntryTypeId > 0) && (ddmFormValuesMap != null)) {
2204                            dlFileEntryMetadataLocalService.updateFileEntryMetadata(
2205                                    fileEntryTypeId, dlFileEntry.getFileEntryId(), fileVersionId,
2206                                    ddmFormValuesMap, serviceContext);
2207                    }
2208    
2209                    return dlFileVersion;
2210            }
2211    
2212            protected void convertExtraSettings(
2213                            DLFileEntry dlFileEntry, DLFileVersion dlFileVersion, String[] keys)
2214                    throws PortalException {
2215    
2216                    UnicodeProperties extraSettingsProperties =
2217                            dlFileVersion.getExtraSettingsProperties();
2218    
2219                    ExpandoBridge expandoBridge = dlFileVersion.getExpandoBridge();
2220    
2221                    convertExtraSettings(extraSettingsProperties, expandoBridge, keys);
2222    
2223                    dlFileVersion.setExtraSettingsProperties(extraSettingsProperties);
2224    
2225                    dlFileVersionPersistence.update(dlFileVersion);
2226    
2227                    int status = dlFileVersion.getStatus();
2228    
2229                    if ((status == WorkflowConstants.STATUS_APPROVED) &&
2230                            (DLUtil.compareVersions(
2231                                    dlFileEntry.getVersion(), dlFileVersion.getVersion()) <= 0)) {
2232    
2233                            reindex(dlFileEntry);
2234                    }
2235            }
2236    
2237            protected void convertExtraSettings(DLFileEntry dlFileEntry, String[] keys)
2238                    throws PortalException {
2239    
2240                    UnicodeProperties extraSettingsProperties =
2241                            dlFileEntry.getExtraSettingsProperties();
2242    
2243                    ExpandoBridge expandoBridge = dlFileEntry.getExpandoBridge();
2244    
2245                    convertExtraSettings(extraSettingsProperties, expandoBridge, keys);
2246    
2247                    dlFileEntry.setExtraSettingsProperties(extraSettingsProperties);
2248    
2249                    dlFileEntryPersistence.update(dlFileEntry);
2250    
2251                    List<DLFileVersion> dlFileVersions =
2252                            dlFileVersionLocalService.getFileVersions(
2253                                    dlFileEntry.getFileEntryId(), WorkflowConstants.STATUS_ANY);
2254    
2255                    for (DLFileVersion dlFileVersion : dlFileVersions) {
2256                            convertExtraSettings(dlFileEntry, dlFileVersion, keys);
2257                    }
2258            }
2259    
2260            protected void convertExtraSettings(
2261                    UnicodeProperties extraSettingsProperties, ExpandoBridge expandoBridge,
2262                    String[] keys) {
2263    
2264                    for (String key : keys) {
2265                            String value = extraSettingsProperties.remove(key);
2266    
2267                            if (Validator.isNull(value)) {
2268                                    continue;
2269                            }
2270    
2271                            int type = expandoBridge.getAttributeType(key);
2272    
2273                            Serializable serializable = ExpandoColumnConstants.getSerializable(
2274                                    type, value);
2275    
2276                            expandoBridge.setAttribute(key, serializable);
2277                    }
2278            }
2279    
2280            protected void copyExpandoRowModifiedDate(
2281                    long companyId, long sourceFileVersionId,
2282                    long destinationFileVersionId) {
2283    
2284                    ExpandoTable expandoTable = expandoTableLocalService.fetchDefaultTable(
2285                            companyId, DLFileEntry.class.getName());
2286    
2287                    if (expandoTable == null) {
2288                            return;
2289                    }
2290    
2291                    ExpandoRow sourceExpandoRow = expandoRowLocalService.fetchRow(
2292                            expandoTable.getTableId(), sourceFileVersionId);
2293    
2294                    if (sourceExpandoRow == null) {
2295                            return;
2296                    }
2297    
2298                    ExpandoRow destinationExpandoRow = expandoRowLocalService.fetchRow(
2299                            expandoTable.getTableId(), destinationFileVersionId);
2300    
2301                    if (destinationExpandoRow == null) {
2302                            return;
2303                    }
2304    
2305                    destinationExpandoRow.setModifiedDate(
2306                            sourceExpandoRow.getModifiedDate());
2307    
2308                    expandoRowLocalService.updateExpandoRow(destinationExpandoRow);
2309            }
2310    
2311            protected void copyFileEntryMetadata(
2312                            long companyId, long fileEntryId, long fromFileVersionId,
2313                            long toFileVersionId, ServiceContext serviceContext,
2314                            Map<String, DDMFormValues> ddmFormValuesMap,
2315                            List<DDMStructure> ddmStructures)
2316                    throws PortalException {
2317    
2318                    for (DDMStructure ddmStructure : ddmStructures) {
2319                            DLFileEntryMetadata dlFileEntryMetadata =
2320                                    dlFileEntryMetadataLocalService.fetchFileEntryMetadata(
2321                                            ddmStructure.getStructureId(), fromFileVersionId);
2322    
2323                            if (dlFileEntryMetadata == null) {
2324                                    continue;
2325                            }
2326    
2327                            DDMFormValues ddmFormValues =
2328                                    StorageEngineManagerUtil.getDDMFormValues(
2329                                            dlFileEntryMetadata.getDDMStorageId());
2330    
2331                            ddmFormValuesMap.put(ddmStructure.getStructureKey(), ddmFormValues);
2332                    }
2333    
2334                    if (!ddmFormValuesMap.isEmpty()) {
2335                            dlFileEntryMetadataLocalService.updateFileEntryMetadata(
2336                                    companyId, ddmStructures, fileEntryId, toFileVersionId,
2337                                    ddmFormValuesMap, serviceContext);
2338                    }
2339            }
2340    
2341            protected RepositoryEventTrigger getFolderRepositoryEventTrigger(
2342                            long groupId, long folderId)
2343                    throws PortalException {
2344    
2345                    if (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
2346                            return RepositoryUtil.getFolderRepositoryEventTrigger(folderId);
2347                    }
2348    
2349                    return RepositoryUtil.getRepositoryEventTrigger(groupId);
2350            }
2351    
2352            protected String getNextVersion(
2353                    DLFileEntry dlFileEntry, boolean majorVersion, int workflowAction) {
2354    
2355                    String version = dlFileEntry.getVersion();
2356    
2357                    DLFileVersion dlFileVersion =
2358                            dlFileVersionLocalService.fetchLatestFileVersion(
2359                                    dlFileEntry.getFileEntryId(), true);
2360    
2361                    if (dlFileVersion != null) {
2362                            version = dlFileVersion.getVersion();
2363                    }
2364    
2365                    if (workflowAction == WorkflowConstants.ACTION_SAVE_DRAFT) {
2366                            majorVersion = false;
2367                    }
2368    
2369                    int[] versionParts = StringUtil.split(version, StringPool.PERIOD, 0);
2370    
2371                    if (majorVersion) {
2372                            versionParts[0]++;
2373                            versionParts[1] = 0;
2374                    }
2375                    else {
2376                            versionParts[1]++;
2377                    }
2378    
2379                    return versionParts[0] + StringPool.PERIOD + versionParts[1];
2380            }
2381    
2382            /**
2383             * @see com.liferay.dynamic.data.lists.service.impl.DDLRecordLocalServiceImpl#isKeepRecordVersionLabel(
2384             *      com.liferay.dynamic.data.lists.model.DDLRecordVersion,
2385             *      com.liferay.dynamic.data.lists.model.DDLRecordVersion,
2386             *      ServiceContext)
2387             */
2388            protected boolean isKeepFileVersionLabel(
2389                            DLFileEntry dlFileEntry, DLFileVersion lastDLFileVersion,
2390                            DLFileVersion latestDLFileVersion, ServiceContext serviceContext)
2391                    throws PortalException {
2392    
2393                    if (PropsValues.DL_FILE_ENTRY_VERSION_POLICY != 1) {
2394                            return false;
2395                    }
2396    
2397                    if (Validator.equals(serviceContext.getCommand(), Constants.REVERT)) {
2398                            return false;
2399                    }
2400    
2401                    if (!Validator.equals(
2402                                    lastDLFileVersion.getTitle(), latestDLFileVersion.getTitle())) {
2403    
2404                            return false;
2405                    }
2406    
2407                    if (!Validator.equals(
2408                                    lastDLFileVersion.getDescription(),
2409                                    latestDLFileVersion.getDescription())) {
2410    
2411                            return false;
2412                    }
2413    
2414                    if (lastDLFileVersion.getFileEntryTypeId() !=
2415                                    latestDLFileVersion.getFileEntryTypeId()) {
2416    
2417                            return false;
2418                    }
2419    
2420                    if (serviceContext.getWorkflowAction() ==
2421                                    WorkflowConstants.ACTION_SAVE_DRAFT) {
2422    
2423                            return false;
2424                    }
2425    
2426                    // File entry type
2427    
2428                    DLFileEntryType dlFileEntryType =
2429                            lastDLFileVersion.getDLFileEntryType();
2430    
2431                    List<DDMStructure> ddmStructures = dlFileEntryType.getDDMStructures();
2432    
2433                    for (DDMStructure ddmStructure : ddmStructures) {
2434                            DLFileEntryMetadata lastFileEntryMetadata =
2435                                    dlFileEntryMetadataLocalService.fetchFileEntryMetadata(
2436                                            ddmStructure.getStructureId(),
2437                                            lastDLFileVersion.getFileVersionId());
2438    
2439                            if (lastFileEntryMetadata == null) {
2440                                    return false;
2441                            }
2442    
2443                            DLFileEntryMetadata latestFileEntryMetadata =
2444                                    dlFileEntryMetadataLocalService.getFileEntryMetadata(
2445                                            ddmStructure.getStructureId(),
2446                                            latestDLFileVersion.getFileVersionId());
2447    
2448                            DDMFormValues lastDDMFormValues =
2449                                    StorageEngineManagerUtil.getDDMFormValues(
2450                                            lastFileEntryMetadata.getDDMStorageId());
2451                            DDMFormValues latestDDMFormValues =
2452                                    StorageEngineManagerUtil.getDDMFormValues(
2453                                            latestFileEntryMetadata.getDDMStorageId());
2454    
2455                            if (!lastDDMFormValues.equals(latestDDMFormValues)) {
2456                                    return false;
2457                            }
2458                    }
2459    
2460                    // Expando
2461    
2462                    ExpandoBridge lastExpandoBridge = lastDLFileVersion.getExpandoBridge();
2463                    ExpandoBridge latestExpandoBridge =
2464                            latestDLFileVersion.getExpandoBridge();
2465    
2466                    Map<String, Serializable> lastAttributes =
2467                            lastExpandoBridge.getAttributes();
2468                    Map<String, Serializable> latestAttributes =
2469                            latestExpandoBridge.getAttributes();
2470    
2471                    if (!lastAttributes.equals(latestAttributes)) {
2472                            return false;
2473                    }
2474    
2475                    // Size
2476    
2477                    long lastSize = lastDLFileVersion.getSize();
2478                    long latestSize = latestDLFileVersion.getSize();
2479    
2480                    if ((lastSize == 0) && (latestSize >= 0)) {
2481                            return true;
2482                    }
2483    
2484                    if (lastSize != latestSize) {
2485                            return false;
2486                    }
2487    
2488                    // Checksum
2489    
2490                    InputStream lastInputStream = null;
2491                    InputStream latestInputStream = null;
2492    
2493                    try {
2494                            String lastChecksum = lastDLFileVersion.getChecksum();
2495    
2496                            if (Validator.isNull(lastChecksum)) {
2497                                    lastInputStream = DLStoreUtil.getFileAsStream(
2498                                            dlFileEntry.getCompanyId(),
2499                                            dlFileEntry.getDataRepositoryId(), dlFileEntry.getName(),
2500                                            lastDLFileVersion.getVersion());
2501    
2502                                    lastChecksum = DigesterUtil.digestBase64(lastInputStream);
2503    
2504                                    lastDLFileVersion.setChecksum(lastChecksum);
2505    
2506                                    dlFileVersionPersistence.update(lastDLFileVersion);
2507                            }
2508    
2509                            latestInputStream = DLStoreUtil.getFileAsStream(
2510                                    dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
2511                                    dlFileEntry.getName(), latestDLFileVersion.getVersion());
2512    
2513                            String latestChecksum = DigesterUtil.digestBase64(
2514                                    latestInputStream);
2515    
2516                            if (lastChecksum.equals(latestChecksum)) {
2517                                    return true;
2518                            }
2519    
2520                            latestDLFileVersion.setChecksum(latestChecksum);
2521    
2522                            dlFileVersionPersistence.update(latestDLFileVersion);
2523                    }
2524                    catch (Exception e) {
2525                            if (_log.isWarnEnabled()) {
2526                                    _log.warn(e, e);
2527                            }
2528                    }
2529                    finally {
2530                            StreamUtil.cleanUp(lastInputStream);
2531                            StreamUtil.cleanUp(latestInputStream);
2532                    }
2533    
2534                    return false;
2535            }
2536    
2537            protected DLFileEntry moveFileEntryImpl(
2538                            long userId, long fileEntryId, long newFolderId,
2539                            ServiceContext serviceContext)
2540                    throws PortalException {
2541    
2542                    // File entry
2543    
2544                    User user = userPersistence.findByPrimaryKey(userId);
2545                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
2546                            fileEntryId);
2547    
2548                    long oldDataRepositoryId = dlFileEntry.getDataRepositoryId();
2549    
2550                    validateFile(
2551                            dlFileEntry.getGroupId(), newFolderId, dlFileEntry.getFileEntryId(),
2552                            dlFileEntry.getFileName(), dlFileEntry.getTitle());
2553    
2554                    dlFileEntry.setFolderId(newFolderId);
2555                    dlFileEntry.setTreePath(dlFileEntry.buildTreePath());
2556    
2557                    dlFileEntryPersistence.update(dlFileEntry);
2558    
2559                    // File version
2560    
2561                    List<DLFileVersion> dlFileVersions =
2562                            dlFileVersionPersistence.findByFileEntryId(fileEntryId);
2563    
2564                    for (DLFileVersion dlFileVersion : dlFileVersions) {
2565                            dlFileVersion.setFolderId(newFolderId);
2566                            dlFileVersion.setTreePath(dlFileVersion.buildTreePath());
2567    
2568                            dlFileVersionPersistence.update(dlFileVersion);
2569                    }
2570    
2571                    // Folder
2572    
2573                    if (newFolderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
2574                            DLFolder dlFolder = dlFolderPersistence.findByPrimaryKey(
2575                                    newFolderId);
2576    
2577                            dlFolder.setModifiedDate(serviceContext.getModifiedDate(null));
2578    
2579                            dlFolderPersistence.update(dlFolder);
2580                    }
2581    
2582                    // File
2583    
2584                    DLStoreUtil.updateFile(
2585                            user.getCompanyId(), oldDataRepositoryId,
2586                            dlFileEntry.getDataRepositoryId(), dlFileEntry.getName());
2587    
2588                    return dlFileEntry;
2589            }
2590    
2591            protected void reindex(DLFileEntry dlFileEntry) throws SearchException {
2592                    Indexer<DLFileEntry> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
2593                            DLFileEntry.class);
2594    
2595                    indexer.reindex(dlFileEntry);
2596            }
2597    
2598            protected void removeFileVersion(
2599                            DLFileEntry dlFileEntry, DLFileVersion dlFileVersion)
2600                    throws PortalException {
2601    
2602                    dlFileVersionPersistence.remove(dlFileVersion);
2603    
2604                    expandoRowLocalService.deleteRows(dlFileVersion.getFileVersionId());
2605    
2606                    dlFileEntryMetadataLocalService.deleteFileVersionFileEntryMetadata(
2607                            dlFileVersion.getFileVersionId());
2608    
2609                    assetEntryLocalService.deleteEntry(
2610                            DLFileEntryConstants.getClassName(), dlFileVersion.getPrimaryKey());
2611    
2612                    DLStoreUtil.deleteFile(
2613                            dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
2614                            dlFileEntry.getName(),
2615                            DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION);
2616    
2617                    unlockFileEntry(dlFileEntry.getFileEntryId());
2618            }
2619    
2620            protected DLFileEntry updateFileEntry(
2621                            long userId, long fileEntryId, String sourceFileName,
2622                            String extension, String mimeType, String title, String description,
2623                            String changeLog, boolean majorVersion, String extraSettings,
2624                            long fileEntryTypeId, Map<String, DDMFormValues> ddmFormValuesMap,
2625                            File file, InputStream is, long size, ServiceContext serviceContext)
2626                    throws PortalException {
2627    
2628                    User user = userPersistence.findByPrimaryKey(userId);
2629                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
2630                            fileEntryId);
2631    
2632                    boolean checkedOut = dlFileEntry.isCheckedOut();
2633    
2634                    DLFileVersion dlFileVersion =
2635                            dlFileVersionLocalService.getLatestFileVersion(
2636                                    fileEntryId, !checkedOut);
2637    
2638                    boolean autoCheckIn = false;
2639    
2640                    if (!checkedOut && dlFileVersion.isApproved() &&
2641                            !Validator.equals(
2642                                    dlFileVersion.getUuid(),
2643                                    serviceContext.getUuidWithoutReset())) {
2644    
2645                            autoCheckIn = true;
2646                    }
2647    
2648                    if (autoCheckIn) {
2649                            dlFileEntry = checkOutFileEntry(
2650                                    userId, fileEntryId, serviceContext);
2651                    }
2652                    else if (!checkedOut) {
2653                            lockFileEntry(userId, fileEntryId);
2654                    }
2655    
2656                    if (!hasFileEntryLock(userId, fileEntryId)) {
2657                            lockFileEntry(userId, fileEntryId);
2658                    }
2659    
2660                    if (checkedOut || autoCheckIn) {
2661                            dlFileVersion = dlFileVersionLocalService.getLatestFileVersion(
2662                                    fileEntryId, false);
2663                    }
2664    
2665                    try {
2666                            if (Validator.isNull(extension)) {
2667                                    extension = dlFileEntry.getExtension();
2668                            }
2669    
2670                            if (Validator.isNull(mimeType)) {
2671                                    mimeType = dlFileEntry.getMimeType();
2672                            }
2673    
2674                            if (Validator.isNull(title)) {
2675                                    title = sourceFileName;
2676    
2677                                    if (Validator.isNull(title)) {
2678                                            title = dlFileEntry.getTitle();
2679                                    }
2680                            }
2681    
2682                            String fileName = DLUtil.getSanitizedFileName(title, extension);
2683    
2684                            Date now = new Date();
2685    
2686                            validateFile(
2687                                    dlFileEntry.getGroupId(), dlFileEntry.getFolderId(),
2688                                    dlFileEntry.getFileEntryId(), sourceFileName, fileName,
2689                                    extension, title);
2690    
2691                            // File version
2692    
2693                            String version = dlFileVersion.getVersion();
2694    
2695                            if (size == 0) {
2696                                    size = dlFileVersion.getSize();
2697                            }
2698    
2699                            updateFileVersion(
2700                                    user, dlFileVersion, sourceFileName, fileName, extension,
2701                                    mimeType, title, description, changeLog, extraSettings,
2702                                    fileEntryTypeId, ddmFormValuesMap, version, size,
2703                                    dlFileVersion.getStatus(), serviceContext.getModifiedDate(now),
2704                                    serviceContext);
2705    
2706                            // Folder
2707    
2708                            if (!checkedOut &&
2709                                    (dlFileEntry.getFolderId() !=
2710                                            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID)) {
2711    
2712                                    dlFolderLocalService.updateLastPostDate(
2713                                            dlFileEntry.getFolderId(),
2714                                            serviceContext.getModifiedDate(now));
2715                            }
2716    
2717                            // File
2718    
2719                            if ((file != null) || (is != null)) {
2720                                    DLStoreUtil.deleteFile(
2721                                            user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
2722                                            dlFileEntry.getName(), version);
2723    
2724                                    if (file != null) {
2725                                            DLStoreUtil.updateFile(
2726                                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
2727                                                    dlFileEntry.getName(), dlFileEntry.getExtension(),
2728                                                    false, version, sourceFileName, file);
2729                                    }
2730                                    else {
2731                                            DLStoreUtil.updateFile(
2732                                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
2733                                                    dlFileEntry.getName(), dlFileEntry.getExtension(),
2734                                                    false, version, sourceFileName, is);
2735                                    }
2736                            }
2737    
2738                            if (autoCheckIn) {
2739                                    if (ExportImportThreadLocal.isImportInProcess()) {
2740                                            checkInFileEntry(
2741                                                    userId, fileEntryId, majorVersion, changeLog,
2742                                                    serviceContext);
2743                                    }
2744                                    else {
2745                                            dlFileEntryService.checkInFileEntry(
2746                                                    fileEntryId, majorVersion, changeLog, serviceContext);
2747                                    }
2748                            }
2749                    }
2750                    catch (PortalException pe) {
2751                            if (autoCheckIn) {
2752                                    try {
2753                                            if (ExportImportThreadLocal.isImportInProcess()) {
2754                                                    cancelCheckOut(userId, fileEntryId);
2755                                            }
2756                                            else {
2757                                                    dlFileEntryService.cancelCheckOut(fileEntryId);
2758                                            }
2759                                    }
2760                                    catch (Exception e) {
2761                                            _log.error(e, e);
2762                                    }
2763                            }
2764    
2765                            throw pe;
2766                    }
2767                    catch (SystemException se) {
2768                            if (autoCheckIn) {
2769                                    try {
2770                                            if (ExportImportThreadLocal.isImportInProcess()) {
2771                                                    cancelCheckOut(userId, fileEntryId);
2772                                            }
2773                                            else {
2774                                                    dlFileEntryService.cancelCheckOut(fileEntryId);
2775                                            }
2776                                    }
2777                                    catch (Exception e) {
2778                                            _log.error(e, e);
2779                                    }
2780                            }
2781    
2782                            throw se;
2783                    }
2784                    finally {
2785                            if (!autoCheckIn && !checkedOut) {
2786                                    unlockFileEntry(fileEntryId);
2787                            }
2788                    }
2789    
2790                    return dlFileEntryPersistence.findByPrimaryKey(fileEntryId);
2791            }
2792    
2793            protected DLFileVersion updateFileVersion(
2794                            User user, DLFileVersion dlFileVersion, String sourceFileName,
2795                            String fileName, String extension, String mimeType, String title,
2796                            String description, String changeLog, String extraSettings,
2797                            long fileEntryTypeId, Map<String, DDMFormValues> ddmFormValuesMap,
2798                            String version, long size, int status, Date statusDate,
2799                            ServiceContext serviceContext)
2800                    throws PortalException {
2801    
2802                    dlFileVersion.setUserId(user.getUserId());
2803                    dlFileVersion.setUserName(user.getFullName());
2804                    dlFileVersion.setModifiedDate(statusDate);
2805                    dlFileVersion.setFileName(fileName);
2806    
2807                    if (Validator.isNotNull(sourceFileName)) {
2808                            dlFileVersion.setExtension(extension);
2809                            dlFileVersion.setMimeType(mimeType);
2810                    }
2811    
2812                    dlFileVersion.setTitle(title);
2813                    dlFileVersion.setDescription(description);
2814                    dlFileVersion.setChangeLog(changeLog);
2815                    dlFileVersion.setExtraSettings(extraSettings);
2816                    dlFileVersion.setFileEntryTypeId(fileEntryTypeId);
2817                    dlFileVersion.setVersion(version);
2818                    dlFileVersion.setSize(size);
2819                    dlFileVersion.setStatus(status);
2820                    dlFileVersion.setStatusByUserId(user.getUserId());
2821                    dlFileVersion.setStatusByUserName(user.getFullName());
2822                    dlFileVersion.setStatusDate(statusDate);
2823    
2824                    ExpandoBridgeUtil.setExpandoBridgeAttributes(
2825                            dlFileVersion.getExpandoBridge(), dlFileVersion.getExpandoBridge(),
2826                            serviceContext);
2827    
2828                    dlFileVersion = dlFileVersionPersistence.update(dlFileVersion);
2829    
2830                    if ((fileEntryTypeId > 0) && (ddmFormValuesMap != null)) {
2831                            dlFileEntryMetadataLocalService.updateFileEntryMetadata(
2832                                    fileEntryTypeId, dlFileVersion.getFileEntryId(),
2833                                    dlFileVersion.getFileVersionId(), ddmFormValuesMap,
2834                                    serviceContext);
2835                    }
2836    
2837                    return dlFileVersion;
2838            }
2839    
2840            protected void validateFile(
2841                            long groupId, long folderId, long fileEntryId,
2842                            String sourceFileName, String fileName, String extension,
2843                            String title)
2844                    throws PortalException {
2845    
2846                    DLValidatorUtil.validateFileName(title);
2847    
2848                    validateFileExtension(extension);
2849    
2850                    validateFile(groupId, folderId, fileEntryId, fileName, title);
2851            }
2852    
2853            protected void validateFileEntryTypeId(
2854                            long[] groupIds, long folderId, long fileEntryTypeId)
2855                    throws PortalException {
2856    
2857                    List<DLFileEntryType> dlFileEntryTypes =
2858                            dlFileEntryTypeLocalService.getFolderFileEntryTypes(
2859                                    groupIds, folderId, true);
2860    
2861                    for (DLFileEntryType dlFileEntryType : dlFileEntryTypes) {
2862                            if (dlFileEntryType.getFileEntryTypeId() == fileEntryTypeId) {
2863                                    return;
2864                            }
2865                    }
2866    
2867                    throw new InvalidFileEntryTypeException(
2868                            "Invalid file entry type " + fileEntryTypeId + " for folder " +
2869                                    folderId);
2870            }
2871    
2872            protected void validateFileExtension(String extension)
2873                    throws PortalException {
2874    
2875                    if (Validator.isNotNull(extension)) {
2876                            int maxLength = ModelHintsUtil.getMaxLength(
2877                                    DLFileEntry.class.getName(), "extension");
2878    
2879                            if (extension.length() > maxLength) {
2880                                    throw new FileExtensionException(
2881                                            extension + " exceeds max length of " + maxLength);
2882                            }
2883                    }
2884            }
2885    
2886            @BeanReference(type = DLFileEntryService.class)
2887            protected DLFileEntryService dlFileEntryService;
2888    
2889            private static final Log _log = LogFactoryUtil.getLog(
2890                    DLFileEntryLocalServiceImpl.class);
2891    
2892    }