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