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