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