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