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