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