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