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