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