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