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