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