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