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