001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.documentlibrary.service.impl;
016    
017    import com.liferay.portal.ExpiredLockException;
018    import com.liferay.portal.InvalidLockException;
019    import com.liferay.portal.NoSuchLockException;
020    import com.liferay.portal.NoSuchModelException;
021    import com.liferay.portal.kernel.exception.PortalException;
022    import com.liferay.portal.kernel.exception.SystemException;
023    import com.liferay.portal.kernel.image.ImageBag;
024    import com.liferay.portal.kernel.image.ImageToolUtil;
025    import com.liferay.portal.kernel.log.Log;
026    import com.liferay.portal.kernel.log.LogFactoryUtil;
027    import com.liferay.portal.kernel.search.Indexer;
028    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
029    import com.liferay.portal.kernel.search.SearchException;
030    import com.liferay.portal.kernel.util.FileUtil;
031    import com.liferay.portal.kernel.util.GetterUtil;
032    import com.liferay.portal.kernel.util.OrderByComparator;
033    import com.liferay.portal.kernel.util.ParamUtil;
034    import com.liferay.portal.kernel.util.PropsKeys;
035    import com.liferay.portal.kernel.util.StringPool;
036    import com.liferay.portal.kernel.util.StringUtil;
037    import com.liferay.portal.kernel.util.UnicodeProperties;
038    import com.liferay.portal.kernel.util.Validator;
039    import com.liferay.portal.kernel.workflow.WorkflowConstants;
040    import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
041    import com.liferay.portal.model.Image;
042    import com.liferay.portal.model.Lock;
043    import com.liferay.portal.model.ResourceConstants;
044    import com.liferay.portal.model.User;
045    import com.liferay.portal.repository.liferayrepository.model.LiferayFileEntry;
046    import com.liferay.portal.repository.liferayrepository.model.LiferayFileVersion;
047    import com.liferay.portal.service.ServiceContext;
048    import com.liferay.portal.util.PortalUtil;
049    import com.liferay.portal.util.PrefsPropsUtil;
050    import com.liferay.portal.util.PropsValues;
051    import com.liferay.portlet.documentlibrary.DuplicateFileException;
052    import com.liferay.portlet.documentlibrary.DuplicateFolderNameException;
053    import com.liferay.portlet.documentlibrary.FileNameException;
054    import com.liferay.portlet.documentlibrary.ImageSizeException;
055    import com.liferay.portlet.documentlibrary.InvalidFileEntryTypeException;
056    import com.liferay.portlet.documentlibrary.NoSuchFileEntryMetadataException;
057    import com.liferay.portlet.documentlibrary.NoSuchFileVersionException;
058    import com.liferay.portlet.documentlibrary.model.DLFileEntry;
059    import com.liferay.portlet.documentlibrary.model.DLFileEntryConstants;
060    import com.liferay.portlet.documentlibrary.model.DLFileEntryMetadata;
061    import com.liferay.portlet.documentlibrary.model.DLFileEntryType;
062    import com.liferay.portlet.documentlibrary.model.DLFileVersion;
063    import com.liferay.portlet.documentlibrary.model.DLFolder;
064    import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
065    import com.liferay.portlet.documentlibrary.model.DLSyncConstants;
066    import com.liferay.portlet.documentlibrary.model.impl.DLFileEntryImpl;
067    import com.liferay.portlet.documentlibrary.service.base.DLFileEntryLocalServiceBaseImpl;
068    import com.liferay.portlet.documentlibrary.store.DLStoreUtil;
069    import com.liferay.portlet.documentlibrary.util.DLUtil;
070    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelModifiedDateComparator;
071    import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
072    import com.liferay.portlet.dynamicdatamapping.storage.Fields;
073    import com.liferay.portlet.dynamicdatamapping.storage.StorageEngineUtil;
074    import com.liferay.portlet.expando.model.ExpandoBridge;
075    import com.liferay.portlet.expando.model.ExpandoColumnConstants;
076    
077    import java.awt.image.RenderedImage;
078    
079    import java.io.File;
080    import java.io.IOException;
081    import java.io.InputStream;
082    import java.io.Serializable;
083    
084    import java.util.Date;
085    import java.util.HashMap;
086    import java.util.List;
087    import java.util.Map;
088    
089    /**
090     * The document library file entry local service.
091     *
092     * <p>
093     * Due to legacy code, the names of some file entry properties are not
094     * intuitive. Each file entry has both a name and title. The <code>name</code>
095     * is a unique identifier for a given file and is generally numeric, whereas the
096     * <code>title</code> is the actual name specified by the user (such as
097     * &quot;Budget.xls&quot;).
098     * </p>
099     *
100     * @author Brian Wing Shun Chan
101     * @author Harry Mark
102     * @author Alexander Chow
103     */
104    public class DLFileEntryLocalServiceImpl
105            extends DLFileEntryLocalServiceBaseImpl {
106    
107            public DLFileEntry addFileEntry(
108                            long userId, long groupId, long repositoryId, long folderId,
109                            String sourceFileName, String mimeType, String title,
110                            String description, String changeLog, long fileEntryTypeId,
111                            Map<String, Fields> fieldsMap, File file, InputStream is, long size,
112                            ServiceContext serviceContext)
113                    throws PortalException, SystemException {
114    
115                    if (Validator.isNull(title)) {
116                            if (size == 0) {
117                                    throw new FileNameException();
118                            }
119                            else {
120                                    title = sourceFileName;
121                            }
122                    }
123    
124                    // File entry
125    
126                    User user = userPersistence.findByPrimaryKey(userId);
127                    folderId = dlFolderLocalService.getFolderId(
128                            user.getCompanyId(), folderId);
129                    String name = String.valueOf(
130                            counterLocalService.increment(DLFileEntry.class.getName()));
131                    String extension = getExtension(title, sourceFileName);
132                    fileEntryTypeId = getFileEntryTypeId(
133                            DLUtil.getGroupIds(groupId), folderId, fileEntryTypeId);
134                    Date now = new Date();
135    
136                    validateFile(groupId, folderId, title, extension, file, is);
137    
138                    long fileEntryId = counterLocalService.increment();
139    
140                    DLFileEntry dlFileEntry = dlFileEntryPersistence.create(fileEntryId);
141    
142                    dlFileEntry.setUuid(serviceContext.getUuid());
143                    dlFileEntry.setGroupId(groupId);
144                    dlFileEntry.setCompanyId(user.getCompanyId());
145                    dlFileEntry.setUserId(user.getUserId());
146                    dlFileEntry.setUserName(user.getFullName());
147                    dlFileEntry.setVersionUserId(user.getUserId());
148                    dlFileEntry.setVersionUserName(user.getFullName());
149                    dlFileEntry.setCreateDate(serviceContext.getCreateDate(now));
150                    dlFileEntry.setModifiedDate(serviceContext.getModifiedDate(now));
151                    dlFileEntry.setRepositoryId(repositoryId);
152                    dlFileEntry.setFolderId(folderId);
153                    dlFileEntry.setName(name);
154                    dlFileEntry.setExtension(extension);
155                    dlFileEntry.setMimeType(mimeType);
156                    dlFileEntry.setTitle(title);
157                    dlFileEntry.setDescription(description);
158                    dlFileEntry.setFileEntryTypeId(fileEntryTypeId);
159                    dlFileEntry.setVersion(DLFileEntryConstants.VERSION_DEFAULT);
160                    dlFileEntry.setSize(size);
161                    dlFileEntry.setReadCount(DLFileEntryConstants.DEFAULT_READ_COUNT);
162    
163                    dlFileEntryPersistence.update(dlFileEntry, false);
164    
165                    // File version
166    
167                    DLFileVersion dlFileVersion = addFileVersion(
168                            user, dlFileEntry, serviceContext.getModifiedDate(now), extension,
169                            mimeType, title, description, null, StringPool.BLANK,
170                            fileEntryTypeId, fieldsMap, DLFileEntryConstants.VERSION_DEFAULT,
171                            size, WorkflowConstants.STATUS_DRAFT, serviceContext);
172    
173                    dlFileEntry.setFileVersion(dlFileVersion);
174    
175                    // Folder
176    
177                    if (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
178                            dlFolderLocalService.updateLastPostDate(
179                                    dlFileEntry.getFolderId(), dlFileEntry.getModifiedDate());
180                    }
181    
182                    // File
183    
184                    if (file != null) {
185                            DLStoreUtil.addFile(
186                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(), name,
187                                    false, file);
188                    }
189                    else {
190                            DLStoreUtil.addFile(
191                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(), name,
192                                    false, is);
193                    }
194    
195                    return dlFileEntry;
196            }
197    
198            public void addFileEntryResources(
199                            DLFileEntry dlFileEntry, boolean addGroupPermissions,
200                            boolean addGuestPermissions)
201                    throws PortalException, SystemException {
202    
203                    resourceLocalService.addResources(
204                            dlFileEntry.getCompanyId(), dlFileEntry.getGroupId(),
205                            dlFileEntry.getUserId(), DLFileEntry.class.getName(),
206                            dlFileEntry.getFileEntryId(), false, addGroupPermissions,
207                            addGuestPermissions);
208            }
209    
210            public void addFileEntryResources(
211                            DLFileEntry dlFileEntry, String[] groupPermissions,
212                            String[] guestPermissions)
213                    throws PortalException, SystemException {
214    
215                    resourceLocalService.addModelResources(
216                            dlFileEntry.getCompanyId(), dlFileEntry.getGroupId(),
217                            dlFileEntry.getUserId(), DLFileEntry.class.getName(),
218                            dlFileEntry.getFileEntryId(), groupPermissions, guestPermissions);
219            }
220    
221            public void cancelCheckOut(long userId, long fileEntryId)
222                    throws PortalException, SystemException {
223    
224                    if (!isFileEntryCheckedOut(fileEntryId)) {
225                            return;
226                    }
227    
228                    if (!hasFileEntryLock(userId, fileEntryId)) {
229                            lockFileEntry(userId, fileEntryId);
230                    }
231    
232                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
233                            fileEntryId);
234    
235                    DLFileVersion dlFileVersion =
236                            dlFileVersionLocalService.getLatestFileVersion(fileEntryId, false);
237    
238                    dlFileVersionPersistence.remove(dlFileVersion);
239    
240                    try {
241                            DLStoreUtil.deleteFile(
242                                    dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
243                                    dlFileEntry.getName(),
244                                    DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION);
245                    }
246                    catch (NoSuchModelException nsme) {
247                    }
248    
249                    lockLocalService.unlock(DLFileEntry.class.getName(), fileEntryId);
250            }
251    
252            public void checkInFileEntry(
253                            long userId, long fileEntryId, boolean majorVersion,
254                            String changeLog, ServiceContext serviceContext)
255                    throws PortalException, SystemException {
256    
257                    if (!isFileEntryCheckedOut(fileEntryId)) {
258                            return;
259                    }
260    
261                    if (!hasFileEntryLock(userId, fileEntryId)) {
262                            lockFileEntry(userId, fileEntryId);
263                    }
264    
265                    User user = userPersistence.findByPrimaryKey(userId);
266                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
267                            fileEntryId);
268    
269                    String version = getNextVersion(
270                            dlFileEntry, majorVersion, serviceContext.getWorkflowAction());
271    
272                    DLFileVersion dlFileVersion =
273                            dlFileVersionLocalService.getLatestFileVersion(fileEntryId, false);
274    
275                    dlFileVersion.setVersion(version);
276                    dlFileVersion.setChangeLog(changeLog);
277    
278                    dlFileVersionPersistence.update(dlFileVersion, false);
279    
280                    // Folder
281    
282                    if (dlFileEntry.getFolderId() !=
283                                    DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
284    
285                            dlFolderLocalService.updateLastPostDate(
286                                    dlFileEntry.getFolderId(), dlFileEntry.getModifiedDate());
287                    }
288    
289                    // File
290    
291                    DLStoreUtil.updateFileVersion(
292                            user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
293                            dlFileEntry.getName(),
294                            DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION, version);
295    
296                    if (serviceContext.getWorkflowAction() ==
297                                    WorkflowConstants.ACTION_PUBLISH) {
298    
299                            startWorkflowInstance(
300                                    userId, serviceContext, dlFileVersion,
301                                    DLSyncConstants.EVENT_UPDATE);
302                    }
303    
304                    lockLocalService.unlock(DLFileEntry.class.getName(), fileEntryId);
305            }
306    
307            public void checkInFileEntry(long userId, long fileEntryId, String lockUuid)
308                    throws PortalException, SystemException {
309    
310                    if (Validator.isNotNull(lockUuid)) {
311                            try {
312                                    Lock lock = lockLocalService.getLock(
313                                            DLFileEntry.class.getName(), fileEntryId);
314    
315                                    if (!lock.getUuid().equals(lockUuid)) {
316                                            throw new InvalidLockException("UUIDs do not match");
317                                    }
318                            }
319                            catch (PortalException pe) {
320                                    if ((pe instanceof ExpiredLockException) ||
321                                            (pe instanceof NoSuchLockException)) {
322                                    }
323                                    else {
324                                            throw pe;
325                                    }
326                            }
327                    }
328    
329                    checkInFileEntry(
330                            userId, fileEntryId, false, StringPool.BLANK, new ServiceContext());
331            }
332    
333            /**
334             * @deprecated {@link #checkOutFileEntry(long, long, ServiceContext)}
335             */
336            public DLFileEntry checkOutFileEntry(long userId, long fileEntryId)
337                    throws PortalException, SystemException {
338    
339                    return checkOutFileEntry(userId, fileEntryId, new ServiceContext());
340            }
341    
342            public DLFileEntry checkOutFileEntry(
343                            long userId, long fileEntryId, ServiceContext serviceContext)
344                    throws PortalException, SystemException {
345    
346                    return checkOutFileEntry(
347                            userId, fileEntryId, StringPool.BLANK,
348                            DLFileEntryImpl.LOCK_EXPIRATION_TIME, serviceContext);
349            }
350    
351            /**
352             * @deprecated {@link #checkOutFileEntry(long, long, String, long,
353             *             ServiceContext)}
354             */
355            public DLFileEntry checkOutFileEntry(
356                            long userId, long fileEntryId, String owner, long expirationTime)
357                    throws PortalException, SystemException {
358    
359                    return checkOutFileEntry(
360                            userId, fileEntryId, owner, expirationTime, new ServiceContext());
361            }
362    
363            public DLFileEntry checkOutFileEntry(
364                            long userId, long fileEntryId, String owner, long expirationTime,
365                            ServiceContext serviceContext)
366                    throws PortalException, SystemException {
367    
368                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
369                            fileEntryId);
370    
371                    boolean hasLock = hasFileEntryLock(userId, fileEntryId);
372    
373                    if (!hasLock) {
374                            if ((expirationTime <= 0) ||
375                                    (expirationTime > DLFileEntryImpl.LOCK_EXPIRATION_TIME)) {
376    
377                                    expirationTime = DLFileEntryImpl.LOCK_EXPIRATION_TIME;
378                            }
379    
380                            lockLocalService.lock(
381                                    userId, DLFileEntry.class.getName(), fileEntryId, owner, false,
382                                    expirationTime);
383                    }
384    
385                    User user = userPersistence.findByPrimaryKey(userId);
386    
387                    serviceContext.setCompanyId(user.getCompanyId());
388                    serviceContext.setUserId(userId);
389    
390                    dlFileEntryPersistence.update(dlFileEntry, false);
391    
392                    DLFileVersion dlFileVersion =
393                            dlFileVersionLocalService.getLatestFileVersion(fileEntryId, false);
394    
395                    long dlFileVersionId = dlFileVersion.getFileVersionId();
396    
397                    String version = dlFileVersion.getVersion();
398    
399                    if (!version.equals(
400                                    DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION)) {
401    
402                            long existingDLFileVersionId = ParamUtil.getLong(
403                                    serviceContext, "existingDLFileVersionId");
404    
405                            if (existingDLFileVersionId > 0) {
406                                    DLFileVersion existingDLFileVersion =
407                                            dlFileVersionPersistence.findByPrimaryKey(
408                                                    existingDLFileVersionId);
409    
410                                    dlFileVersion = updateFileVersion(
411                                            user, existingDLFileVersion, null,
412                                            existingDLFileVersion.getExtension(),
413                                            existingDLFileVersion.getMimeType(),
414                                            existingDLFileVersion.getTitle(),
415                                            existingDLFileVersion.getDescription(),
416                                            existingDLFileVersion.getChangeLog(),
417                                            existingDLFileVersion.getExtraSettings(),
418                                            existingDLFileVersion.getFileEntryTypeId(), null,
419                                            DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION,
420                                            existingDLFileVersion.getSize(),
421                                            WorkflowConstants.STATUS_DRAFT, new Date(), serviceContext);
422                            }
423                            else {
424                                    dlFileVersion = addFileVersion(
425                                            user, dlFileEntry, new Date(), dlFileVersion.getExtension(),
426                                            dlFileVersion.getMimeType(), dlFileVersion.getTitle(),
427                                            dlFileVersion.getDescription(),
428                                            dlFileVersion.getChangeLog(),
429                                            dlFileVersion.getExtraSettings(),
430                                            dlFileVersion.getFileEntryTypeId(), null,
431                                            DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION,
432                                            dlFileVersion.getSize(), WorkflowConstants.STATUS_DRAFT,
433                                            serviceContext);
434                            }
435    
436                            try {
437                                    DLStoreUtil.deleteFile(
438                                            dlFileEntry.getCompanyId(),
439                                            dlFileEntry.getDataRepositoryId(), dlFileEntry.getName(),
440                                            DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION);
441                            }
442                            catch (NoSuchModelException nsme) {
443                            }
444    
445                            DLStoreUtil.copyFileVersion(
446                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
447                                    dlFileEntry.getName(), version,
448                                    DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION);
449    
450                            copyFileEntryMetadata(
451                                    dlFileEntry.getCompanyId(), dlFileVersion.getFileEntryTypeId(),
452                                    fileEntryId, dlFileVersionId, dlFileVersion.getFileVersionId(),
453                                    serviceContext);
454                    }
455    
456                    return dlFileEntry;
457            }
458    
459            public void convertExtraSettings(String[] keys)
460                    throws PortalException, SystemException {
461    
462                    int count = dlFileEntryFinder.countByExtraSettings();
463    
464                    int pages = count / Indexer.DEFAULT_INTERVAL;
465    
466                    for (int i = 0; i <= pages; i++) {
467                            int start = (i * Indexer.DEFAULT_INTERVAL);
468                            int end = start + Indexer.DEFAULT_INTERVAL;
469    
470                            List<DLFileEntry> dlFileEntries =
471                                    dlFileEntryFinder.findByExtraSettings(start, end);
472    
473                            for (DLFileEntry dlFileEntry : dlFileEntries) {
474                                    convertExtraSettings(dlFileEntry, keys);
475                            }
476                    }
477            }
478    
479            public void copyFileEntryMetadata(
480                            long companyId, long fileEntryTypeId, long fileEntryId,
481                            long fromFileVersionId, long toFileVersionId,
482                            ServiceContext serviceContext)
483                    throws PortalException, SystemException {
484    
485                    Map<String, Fields> fieldsMap = new HashMap<String, Fields>();
486    
487                    List<DDMStructure> ddmStructures = null;
488    
489                    if (fileEntryTypeId > 0) {
490                            DLFileEntryType dlFileEntryType =
491                                    dlFileEntryTypeLocalService.getFileEntryType(fileEntryTypeId);
492    
493                            ddmStructures = dlFileEntryType.getDDMStructures();
494    
495                            for (DDMStructure ddmStructure : ddmStructures) {
496                                    try {
497                                            DLFileEntryMetadata dlFileEntryMetadata =
498                                                    dlFileEntryMetadataLocalService.getFileEntryMetadata(
499                                                            ddmStructure.getStructureId(), fromFileVersionId);
500    
501                                            Fields fields = StorageEngineUtil.getFields(
502                                                    dlFileEntryMetadata.getDDMStorageId());
503    
504                                            fieldsMap.put(ddmStructure.getStructureKey(), fields);
505                                    }
506                                    catch (NoSuchFileEntryMetadataException nsfeme) {
507                                    }
508                            }
509    
510                            dlFileEntryMetadataLocalService.updateFileEntryMetadata(
511                                    companyId, ddmStructures, fileEntryTypeId, fileEntryId,
512                                    toFileVersionId, fieldsMap, serviceContext);
513                    }
514    
515                    long classNameId = PortalUtil.getClassNameId(DLFileEntry.class);
516    
517                    ddmStructures = ddmStructureLocalService.getClassStructures(
518                            classNameId);
519    
520                    for (DDMStructure ddmStructure : ddmStructures) {
521                            try {
522                                    DLFileEntryMetadata fileEntryMetadata =
523                                            dlFileEntryMetadataLocalService.getFileEntryMetadata(
524                                                    ddmStructure.getStructureId(), fromFileVersionId);
525    
526                                    Fields fields = StorageEngineUtil.getFields(
527                                            fileEntryMetadata.getDDMStorageId());
528    
529                                    fieldsMap.put(ddmStructure.getStructureKey(), fields);
530                            }
531                            catch (NoSuchFileEntryMetadataException nsfme) {
532                            }
533                    }
534    
535                    dlFileEntryMetadataLocalService.updateFileEntryMetadata(
536                            companyId, ddmStructures, fileEntryTypeId, fileEntryId,
537                            toFileVersionId, fieldsMap, serviceContext);
538            }
539    
540            public void deleteFileEntries(long groupId, long folderId)
541                    throws PortalException, SystemException {
542    
543                    int count = dlFileEntryPersistence.countByG_F(groupId, folderId);
544    
545                    int pages = count / _DELETE_INTERVAL;
546    
547                    for (int i = 0; i <= pages; i++) {
548                            int start = (i * _DELETE_INTERVAL);
549                            int end = start + _DELETE_INTERVAL;
550    
551                            List<DLFileEntry> dlFileEntries = dlFileEntryPersistence.findByG_F(
552                                    groupId, folderId, start, end);
553    
554                            for (DLFileEntry dlFileEntry : dlFileEntries) {
555                                    dlAppHelperLocalService.deleteFileEntry(
556                                            new LiferayFileEntry(dlFileEntry));
557    
558                                    deleteFileEntry(dlFileEntry);
559                            }
560                    }
561            }
562    
563            public void deleteFileEntry(long fileEntryId)
564                    throws PortalException, SystemException {
565    
566                    DLFileEntry dlFileEntry = getFileEntry(fileEntryId);
567    
568                    deleteFileEntry(dlFileEntry);
569            }
570    
571            public void deleteFileEntry(long userId, long fileEntryId)
572                    throws PortalException, SystemException {
573    
574                    if (!hasFileEntryLock(userId, fileEntryId)) {
575                            lockFileEntry(userId, fileEntryId);
576                    }
577    
578                    try {
579                            deleteFileEntry(fileEntryId);
580                    }
581                    finally {
582                            unlockFileEntry(fileEntryId);
583                    }
584            }
585    
586            public DLFileEntry fetchFileEntryByAnyImageId(long imageId)
587                    throws SystemException {
588    
589                    return dlFileEntryFinder.fetchByAnyImageId(imageId);
590            }
591    
592            public List<DLFileEntry> getExtraSettingsFileEntries(int start, int end)
593                    throws SystemException {
594    
595                    return dlFileEntryFinder.findByExtraSettings(start, end);
596            }
597    
598            public File getFile(
599                            long userId, long fileEntryId, String version,
600                            boolean incrementCounter)
601                    throws PortalException, SystemException {
602    
603                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
604                            fileEntryId);
605    
606                    if (PropsValues.DL_FILE_ENTRY_READ_COUNT_ENABLED && incrementCounter) {
607                            dlFileEntry.setReadCount(dlFileEntry.getReadCount() + 1);
608    
609                            dlFileEntryPersistence.update(dlFileEntry, false);
610                    }
611    
612                    dlAppHelperLocalService.getFileAsStream(
613                            userId, new LiferayFileEntry(dlFileEntry), incrementCounter);
614    
615                    return DLStoreUtil.getFile(
616                            dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
617                            dlFileEntry.getName(), version);
618            }
619    
620            public InputStream getFileAsStream(
621                            long userId, long fileEntryId, String version)
622                    throws PortalException, SystemException {
623    
624                    return getFileAsStream(userId, fileEntryId, version, true);
625            }
626    
627            public InputStream getFileAsStream(
628                            long userId, long fileEntryId, String version,
629                            boolean incrementCounter)
630                    throws PortalException, SystemException {
631    
632                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
633                            fileEntryId);
634    
635                    if (PropsValues.DL_FILE_ENTRY_READ_COUNT_ENABLED && incrementCounter) {
636                            dlFileEntry.setReadCount(dlFileEntry.getReadCount() + 1);
637    
638                            dlFileEntryPersistence.update(dlFileEntry, false);
639                    }
640    
641                    dlAppHelperLocalService.getFileAsStream(
642                            userId, new LiferayFileEntry(dlFileEntry), incrementCounter);
643    
644                    return DLStoreUtil.getFileAsStream(
645                            dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
646                            dlFileEntry.getName(), version);
647            }
648    
649            public List<DLFileEntry> getFileEntries(int start, int end)
650                    throws SystemException {
651    
652                    return dlFileEntryPersistence.findAll(start, end);
653            }
654    
655            public List<DLFileEntry> getFileEntries(
656                            long groupId, long folderId, int start, int end,
657                            OrderByComparator obc)
658                    throws SystemException {
659    
660                    return dlFileEntryPersistence.findByG_F(
661                            groupId, folderId, start, end, obc);
662            }
663    
664            public int getFileEntriesCount() throws SystemException {
665                    return dlFileEntryPersistence.countAll();
666            }
667    
668            public int getFileEntriesCount(long groupId, long folderId)
669                    throws SystemException {
670    
671                    return dlFileEntryPersistence.countByG_F(groupId, folderId);
672            }
673    
674            public DLFileEntry getFileEntry(long fileEntryId)
675                    throws PortalException, SystemException {
676    
677                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
678                            fileEntryId);
679    
680                    DLFileVersion dlFileVersion = dlFileVersionLocalService.getFileVersion(
681                            fileEntryId, dlFileEntry.getVersion());
682    
683                    dlFileEntry.setFileVersion(dlFileVersion);
684    
685                    return dlFileEntry;
686            }
687    
688            public DLFileEntry getFileEntry(long groupId, long folderId, String title)
689                    throws PortalException, SystemException {
690    
691                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByG_F_T(
692                            groupId, folderId, title);
693    
694                    DLFileVersion dlFileVersion = dlFileVersionLocalService.getFileVersion(
695                            dlFileEntry.getFileEntryId(), dlFileEntry.getVersion());
696    
697                    dlFileEntry.setFileVersion(dlFileVersion);
698    
699                    return dlFileEntry;
700            }
701    
702            public DLFileEntry getFileEntryByName(
703                            long groupId, long folderId, String name)
704                    throws PortalException, SystemException {
705    
706                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByG_F_N(
707                            groupId, folderId, name);
708    
709                    DLFileVersion dlFileVersion = dlFileVersionLocalService.getFileVersion(
710                            dlFileEntry.getFileEntryId(), dlFileEntry.getVersion());
711    
712                    dlFileEntry.setFileVersion(dlFileVersion);
713    
714                    return dlFileEntry;
715            }
716    
717            public DLFileEntry getFileEntryByUuidAndGroupId(String uuid, long groupId)
718                    throws PortalException, SystemException {
719    
720                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByUUID_G(
721                            uuid, groupId);
722    
723                    DLFileVersion dlFileVersion = dlFileVersionLocalService.getFileVersion(
724                            dlFileEntry.getFileEntryId(), dlFileEntry.getVersion());
725    
726                    dlFileEntry.setFileVersion(dlFileVersion);
727    
728                    return dlFileEntry;
729            }
730    
731            public List<DLFileEntry> getGroupFileEntries(
732                            long groupId, int start, int end)
733                    throws SystemException {
734    
735                    return getGroupFileEntries(
736                            groupId, start, end, new RepositoryModelModifiedDateComparator());
737            }
738    
739            public List<DLFileEntry> getGroupFileEntries(
740                            long groupId, int start, int end, OrderByComparator obc)
741                    throws SystemException {
742    
743                    return dlFileEntryPersistence.findByGroupId(groupId, start, end, obc);
744            }
745    
746            public List<DLFileEntry> getGroupFileEntries(
747                            long groupId, long userId, int start, int end)
748                    throws SystemException {
749    
750                    return getGroupFileEntries(
751                            groupId, userId, start, end,
752                            new RepositoryModelModifiedDateComparator());
753            }
754    
755            public List<DLFileEntry> getGroupFileEntries(
756                            long groupId, long userId, int start, int end,
757                            OrderByComparator obc)
758                    throws SystemException {
759    
760                    if (userId <= 0) {
761                            return dlFileEntryPersistence.findByGroupId(
762                                    groupId, start, end, obc);
763                    }
764                    else {
765                            return dlFileEntryPersistence.findByG_U(
766                                    groupId, userId, start, end, obc);
767                    }
768            }
769    
770            public int getGroupFileEntriesCount(long groupId) throws SystemException {
771                    return dlFileEntryPersistence.countByGroupId(groupId);
772            }
773    
774            public int getGroupFileEntriesCount(long groupId, long userId)
775                    throws SystemException {
776    
777                    if (userId <= 0) {
778                            return dlFileEntryPersistence.countByGroupId(groupId);
779                    }
780                    else {
781                            return dlFileEntryPersistence.countByG_U(groupId, userId);
782                    }
783            }
784    
785            public List<DLFileEntry> getNoAssetFileEntries() throws SystemException {
786                    return dlFileEntryFinder.findByNoAssets();
787            }
788    
789            public List<DLFileEntry> getOrphanedFileEntries() throws SystemException {
790                    return dlFileEntryFinder.findByOrphanedFileEntries();
791            }
792    
793            public boolean hasExtraSettings() throws SystemException {
794                    if (dlFileEntryFinder.countByExtraSettings() > 0) {
795                            return true;
796                    }
797                    else {
798                            return false;
799                    }
800            }
801    
802            public boolean hasFileEntryLock(long userId, long fileEntryId)
803                    throws PortalException, SystemException {
804    
805                    DLFileEntry dlFileEntry = getFileEntry(fileEntryId);
806    
807                    long folderId = dlFileEntry.getFolderId();
808    
809                    boolean hasLock = lockLocalService.hasLock(
810                            userId, DLFileEntry.class.getName(), fileEntryId);
811    
812                    if (!hasLock &&
813                            (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID)) {
814    
815                            hasLock = dlFolderService.hasInheritableLock(folderId);
816                    }
817    
818                    return hasLock;
819            }
820    
821            public boolean isFileEntryCheckedOut(long fileEntryId)
822                    throws PortalException, SystemException {
823    
824                    DLFileVersion dlFileVersion =
825                            dlFileVersionLocalService.getLatestFileVersion(fileEntryId, false);
826    
827                    String version = dlFileVersion.getVersion();
828    
829                    if (version.equals(DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION)) {
830                            return true;
831                    }
832                    else {
833                            return false;
834                    }
835            }
836    
837            public Lock lockFileEntry(long userId, long fileEntryId)
838                    throws PortalException, SystemException {
839    
840                    return lockFileEntry(
841                            userId, fileEntryId, null, DLFileEntryImpl.LOCK_EXPIRATION_TIME);
842            }
843    
844            public Lock lockFileEntry(
845                            long userId, long fileEntryId, String owner, long expirationTime)
846                    throws PortalException, SystemException {
847    
848                    if (hasFileEntryLock(userId, fileEntryId)) {
849                            return lockLocalService.getLock(
850                                    DLFileEntry.class.getName(), fileEntryId);
851                    }
852    
853                    if ((expirationTime <= 0) ||
854                            (expirationTime > DLFileEntryImpl.LOCK_EXPIRATION_TIME)) {
855    
856                            expirationTime = DLFileEntryImpl.LOCK_EXPIRATION_TIME;
857                    }
858    
859                    return lockLocalService.lock(
860                            userId, DLFileEntry.class.getName(), fileEntryId, owner, false,
861                            expirationTime);
862            }
863    
864            public DLFileEntry moveFileEntry(
865                            long userId, long fileEntryId, long newFolderId,
866                            ServiceContext serviceContext)
867                    throws PortalException, SystemException {
868    
869                    if (!hasFileEntryLock(userId, fileEntryId)) {
870                            lockFileEntry(userId, fileEntryId);
871                    }
872    
873                    try {
874                            DLFileEntry dlFileEntry = moveFileEntryImpl(
875                                    userId, fileEntryId, newFolderId, serviceContext);
876    
877                            dlAppHelperLocalService.moveFileEntry(
878                                    new LiferayFileEntry(dlFileEntry));
879    
880                            return dlFileEntryTypeLocalService.updateFileEntryFileEntryType(
881                                    dlFileEntry, serviceContext);
882                    }
883                    finally {
884                            if (!isFileEntryCheckedOut(fileEntryId)) {
885                                    unlockFileEntry(fileEntryId);
886                            }
887                    }
888            }
889    
890            public void revertFileEntry(
891                            long userId, long fileEntryId, String version,
892                            ServiceContext serviceContext)
893                    throws PortalException, SystemException {
894    
895                    DLFileVersion dlFileVersion = dlFileVersionLocalService.getFileVersion(
896                            fileEntryId, version);
897    
898                    if (!dlFileVersion.isApproved()) {
899                            return;
900                    }
901    
902                    String sourceFileName = dlFileVersion.getTitle();
903                    String extension = dlFileVersion.getExtension();
904                    String mimeType = dlFileVersion.getMimeType();
905                    String title = dlFileVersion.getTitle();
906                    String description = dlFileVersion.getDescription();
907                    String changeLog = "Reverted to " + version;
908                    boolean majorVersion = true;
909                    String extraSettings = dlFileVersion.getExtraSettings();
910                    long fileEntryTypeId = dlFileVersion.getFileEntryTypeId();
911                    Map<String, Fields> fieldsMap = null;
912                    InputStream is = getFileAsStream(userId, fileEntryId, version);
913                    long size = dlFileVersion.getSize();
914    
915                    DLFileEntry dlFileEntry = updateFileEntry(
916                            userId, fileEntryId, sourceFileName, extension, mimeType, title,
917                            description, changeLog, majorVersion, extraSettings,
918                            fileEntryTypeId, fieldsMap, null, is, size, serviceContext);
919    
920                    DLFileVersion newDlFileVersion =
921                            dlFileVersionLocalService.getFileVersion(
922                                    fileEntryId, dlFileEntry.getVersion());
923    
924                    copyFileEntryMetadata(
925                            dlFileVersion.getCompanyId(), dlFileVersion.getFileEntryTypeId(),
926                            fileEntryId, newDlFileVersion.getFileVersionId(),
927                            dlFileVersion.getFileVersionId(), serviceContext);
928            }
929    
930            public void unlockFileEntry(long fileEntryId) throws SystemException {
931                    lockLocalService.unlock(DLFileEntry.class.getName(), fileEntryId);
932            }
933    
934            public void unlockFileEntry(long fileEntryId, String lockUuid)
935                    throws PortalException, SystemException {
936    
937                    if (Validator.isNotNull(lockUuid)) {
938                            try {
939                                    Lock lock = lockLocalService.getLock(
940                                            DLFileEntry.class.getName(), fileEntryId);
941    
942                                    if (!lock.getUuid().equals(lockUuid)) {
943                                            throw new InvalidLockException("UUIDs do not match");
944                                    }
945                            }
946                            catch (PortalException pe) {
947                                    if ((pe instanceof ExpiredLockException) ||
948                                            (pe instanceof NoSuchLockException)) {
949                                    }
950                                    else {
951                                            throw pe;
952                                    }
953                            }
954                    }
955    
956                    if (!isFileEntryCheckedOut(fileEntryId)) {
957                            lockLocalService.unlock(DLFileEntry.class.getName(), fileEntryId);
958                    }
959            }
960    
961            public DLFileEntry updateFileEntry(
962                            long userId, long fileEntryId, String sourceFileName,
963                            String mimeType, String title, String description, String changeLog,
964                            boolean majorVersion, long fileEntryTypeId,
965                            Map<String, Fields> fieldsMap, File file, InputStream is, long size,
966                            ServiceContext serviceContext)
967                    throws PortalException, SystemException {
968    
969                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
970                            fileEntryId);
971    
972                    String extension = getExtension(title, sourceFileName);
973    
974                    String extraSettings = StringPool.BLANK;
975    
976                    fileEntryTypeId = getFileEntryTypeId(
977                            DLUtil.getGroupIds(dlFileEntry.getGroupId()),
978                            dlFileEntry.getFolderId(), fileEntryTypeId);
979    
980                    return updateFileEntry(
981                            userId, fileEntryId, sourceFileName, extension, mimeType, title,
982                            description, changeLog, majorVersion, extraSettings,
983                            fileEntryTypeId, fieldsMap, file, is, size, serviceContext);
984            }
985    
986            public void updateSmallImage(long smallImageId, long largeImageId)
987                    throws PortalException, SystemException {
988    
989                    try {
990                            RenderedImage renderedImage = null;
991    
992                            Image largeImage = imageLocalService.getImage(largeImageId);
993    
994                            byte[] bytes = largeImage.getTextObj();
995                            String contentType = largeImage.getType();
996    
997                            if (bytes != null) {
998                                    ImageBag imageBag = ImageToolUtil.read(bytes);
999    
1000                                    renderedImage = imageBag.getRenderedImage();
1001    
1002                                    //validate(bytes);
1003                            }
1004    
1005                            if (renderedImage != null) {
1006                                    int height = PrefsPropsUtil.getInteger(
1007                                            PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_HEIGHT);
1008                                    int width = PrefsPropsUtil.getInteger(
1009                                            PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_WIDTH);
1010    
1011                                    RenderedImage thumbnailRenderedImage = ImageToolUtil.scale(
1012                                            renderedImage, height, width);
1013    
1014                                    imageLocalService.updateImage(
1015                                            smallImageId,
1016                                            ImageToolUtil.getBytes(
1017                                                    thumbnailRenderedImage, contentType));
1018                            }
1019                    }
1020                    catch (IOException ioe) {
1021                            throw new ImageSizeException(ioe);
1022                    }
1023            }
1024    
1025            public DLFileEntry updateStatus(
1026                            long userId, long fileVersionId, int status,
1027                            Map<String, Serializable> workflowContext,
1028                            ServiceContext serviceContext)
1029                    throws PortalException, SystemException {
1030    
1031                    // File version
1032    
1033                    User user = userPersistence.findByPrimaryKey(userId);
1034    
1035                    DLFileVersion dlFileVersion = dlFileVersionPersistence.findByPrimaryKey(
1036                            fileVersionId);
1037    
1038                    dlFileVersion.setStatus(status);
1039                    dlFileVersion.setStatusByUserId(user.getUserId());
1040                    dlFileVersion.setStatusByUserName(user.getFullName());
1041                    dlFileVersion.setStatusDate(new Date());
1042    
1043                    dlFileVersionPersistence.update(dlFileVersion, false);
1044    
1045                    // File entry
1046    
1047                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
1048                            dlFileVersion.getFileEntryId());
1049    
1050                    if (status == WorkflowConstants.STATUS_APPROVED) {
1051                            if (DLUtil.compareVersions(
1052                                            dlFileEntry.getVersion(),
1053                                            dlFileVersion.getVersion()) <= 0) {
1054    
1055                                    dlFileEntry.setExtension(dlFileVersion.getExtension());
1056                                    dlFileEntry.setTitle(dlFileVersion.getTitle());
1057                                    dlFileEntry.setDescription(dlFileVersion.getDescription());
1058                                    dlFileEntry.setExtraSettings(dlFileVersion.getExtraSettings());
1059                                    dlFileEntry.setFileEntryTypeId(
1060                                            dlFileVersion.getFileEntryTypeId());
1061                                    dlFileEntry.setVersion(dlFileVersion.getVersion());
1062                                    dlFileEntry.setVersionUserId(dlFileVersion.getUserId());
1063                                    dlFileEntry.setVersionUserName(dlFileVersion.getUserName());
1064                                    dlFileEntry.setModifiedDate(dlFileVersion.getCreateDate());
1065                                    dlFileEntry.setSize(dlFileVersion.getSize());
1066    
1067                                    dlFileEntryPersistence.update(dlFileEntry, false);
1068                            }
1069                    }
1070                    else {
1071    
1072                            // File entry
1073    
1074                            if (dlFileEntry.getVersion().equals(dlFileVersion.getVersion())) {
1075                                    String newVersion = DLFileEntryConstants.VERSION_DEFAULT;
1076    
1077                                    List<DLFileVersion> approvedFileVersions =
1078                                            dlFileVersionPersistence.findByF_S(
1079                                                    dlFileEntry.getFileEntryId(),
1080                                                    WorkflowConstants.STATUS_APPROVED);
1081    
1082                                    if (!approvedFileVersions.isEmpty()) {
1083                                            newVersion = approvedFileVersions.get(0).getVersion();
1084                                    }
1085    
1086                                    dlFileEntry.setVersion(newVersion);
1087    
1088                                    dlFileEntryPersistence.update(dlFileEntry, false);
1089                            }
1090    
1091                            // Indexer
1092    
1093                            if (dlFileVersion.getVersion().equals(
1094                                            DLFileEntryConstants.VERSION_DEFAULT)) {
1095    
1096                                    Indexer indexer = IndexerRegistryUtil.getIndexer(
1097                                            DLFileEntry.class);
1098    
1099                                    indexer.delete(dlFileEntry);
1100                            }
1101                    }
1102    
1103                    // App helper
1104    
1105                    dlAppHelperLocalService.updateStatus(
1106                            userId, new LiferayFileEntry(dlFileEntry),
1107                            new LiferayFileVersion(dlFileVersion), status, workflowContext);
1108    
1109                    // Indexer
1110    
1111                    if (status == WorkflowConstants.STATUS_APPROVED) {
1112                            reindex(dlFileEntry);
1113                    }
1114    
1115                    return dlFileEntry;
1116            }
1117    
1118            public boolean verifyFileEntryCheckOut(long fileEntryId, String lockUuid)
1119                    throws PortalException, SystemException {
1120    
1121                    if (verifyFileEntryLock(fileEntryId, lockUuid) &&
1122                            isFileEntryCheckedOut(fileEntryId)) {
1123    
1124                            return true;
1125                    }
1126                    else {
1127                            return false;
1128                    }
1129            }
1130    
1131            public boolean verifyFileEntryLock(long fileEntryId, String lockUuid)
1132                    throws PortalException, SystemException {
1133    
1134                    boolean lockVerified = false;
1135    
1136                    try {
1137                            Lock lock = lockLocalService.getLock(
1138                                    DLFileEntry.class.getName(), fileEntryId);
1139    
1140                            if (lock.getUuid().equals(lockUuid)) {
1141                                    lockVerified = true;
1142                            }
1143                    }
1144                    catch (PortalException pe) {
1145                            if ((pe instanceof ExpiredLockException) ||
1146                                    (pe instanceof NoSuchLockException)) {
1147    
1148                                    DLFileEntry dlFileEntry = dlFileEntryLocalService.getFileEntry(
1149                                            fileEntryId);
1150    
1151                                    lockVerified = dlFolderService.verifyInheritableLock(
1152                                            dlFileEntry.getFolderId(), lockUuid);
1153                            }
1154                            else {
1155                                    throw pe;
1156                            }
1157                    }
1158    
1159                    return lockVerified;
1160            }
1161    
1162            protected DLFileVersion addFileVersion(
1163                            User user, DLFileEntry dlFileEntry, Date modifiedDate,
1164                            String extension, String mimeType, String title, String description,
1165                            String changeLog, String extraSettings, long fileEntryTypeId,
1166                            Map<String, Fields> fieldsMap, String version, long size,
1167                            int status, ServiceContext serviceContext)
1168                    throws PortalException, SystemException {
1169    
1170                    long fileVersionId = counterLocalService.increment();
1171    
1172                    DLFileVersion dlFileVersion = dlFileVersionPersistence.create(
1173                            fileVersionId);
1174    
1175                    String uuid = ParamUtil.getString(
1176                            serviceContext, "fileVersionUuid", serviceContext.getUuid());
1177    
1178                    dlFileVersion.setUuid(uuid);
1179    
1180                    dlFileVersion.setGroupId(dlFileEntry.getGroupId());
1181                    dlFileVersion.setCompanyId(dlFileEntry.getCompanyId());
1182    
1183                    long versionUserId = dlFileEntry.getVersionUserId();
1184    
1185                    if (versionUserId <= 0) {
1186                            versionUserId = dlFileEntry.getUserId();
1187                    }
1188    
1189                    dlFileVersion.setUserId(versionUserId);
1190    
1191                    String versionUserName = GetterUtil.getString(
1192                            dlFileEntry.getVersionUserName(), dlFileEntry.getUserName());
1193    
1194                    dlFileVersion.setUserName(versionUserName);
1195    
1196                    dlFileVersion.setCreateDate(modifiedDate);
1197                    dlFileVersion.setModifiedDate(modifiedDate);
1198                    dlFileVersion.setRepositoryId(dlFileEntry.getRepositoryId());
1199                    dlFileVersion.setFolderId(dlFileEntry.getFolderId());
1200                    dlFileVersion.setFileEntryId(dlFileEntry.getFileEntryId());
1201                    dlFileVersion.setExtension(extension);
1202                    dlFileVersion.setMimeType(mimeType);
1203                    dlFileVersion.setTitle(title);
1204                    dlFileVersion.setDescription(description);
1205                    dlFileVersion.setChangeLog(changeLog);
1206                    dlFileVersion.setExtraSettings(extraSettings);
1207                    dlFileVersion.setFileEntryTypeId(fileEntryTypeId);
1208                    dlFileVersion.setVersion(version);
1209                    dlFileVersion.setSize(size);
1210                    dlFileVersion.setStatus(status);
1211                    dlFileVersion.setStatusByUserId(user.getUserId());
1212                    dlFileVersion.setStatusByUserName(user.getFullName());
1213                    dlFileVersion.setStatusDate(dlFileEntry.getModifiedDate());
1214                    dlFileVersion.setExpandoBridgeAttributes(serviceContext);
1215    
1216                    dlFileVersionPersistence.update(dlFileVersion, false);
1217    
1218                    if ((fileEntryTypeId > 0) && (fieldsMap != null)) {
1219                            dlFileEntryMetadataLocalService.updateFileEntryMetadata(
1220                                    fileEntryTypeId, dlFileEntry.getFileEntryId(), fileVersionId,
1221                                    fieldsMap, serviceContext);
1222                    }
1223    
1224                    return dlFileVersion;
1225            }
1226    
1227            protected void convertExtraSettings(
1228                            DLFileEntry dlFileEntry, DLFileVersion dlFileVersion, String[] keys)
1229                    throws PortalException, SystemException {
1230    
1231                    UnicodeProperties extraSettingsProperties =
1232                            dlFileVersion.getExtraSettingsProperties();
1233    
1234                    ExpandoBridge expandoBridge = dlFileVersion.getExpandoBridge();
1235    
1236                    convertExtraSettings(extraSettingsProperties, expandoBridge, keys);
1237    
1238                    dlFileVersion.setExtraSettingsProperties(extraSettingsProperties);
1239    
1240                    dlFileVersionPersistence.update(dlFileVersion, false);
1241    
1242                    int status = dlFileVersion.getStatus();
1243    
1244                    if ((status == WorkflowConstants.STATUS_APPROVED) &&
1245                            (DLUtil.compareVersions(
1246                                    dlFileEntry.getVersion(), dlFileVersion.getVersion()) <= 0)) {
1247    
1248                            reindex(dlFileEntry);
1249                    }
1250            }
1251    
1252            protected void convertExtraSettings(DLFileEntry dlFileEntry, String[] keys)
1253                    throws PortalException, SystemException {
1254    
1255                    UnicodeProperties extraSettingsProperties =
1256                            dlFileEntry.getExtraSettingsProperties();
1257    
1258                    ExpandoBridge expandoBridge = dlFileEntry.getExpandoBridge();
1259    
1260                    convertExtraSettings(extraSettingsProperties, expandoBridge, keys);
1261    
1262                    dlFileEntry.setExtraSettingsProperties(extraSettingsProperties);
1263    
1264                    dlFileEntryPersistence.update(dlFileEntry, false);
1265    
1266                    List<DLFileVersion> dlFileVersions =
1267                            dlFileVersionLocalService.getFileVersions(
1268                                    dlFileEntry.getFileEntryId(), WorkflowConstants.STATUS_ANY);
1269    
1270                    for (DLFileVersion dlFileVersion : dlFileVersions) {
1271                            convertExtraSettings(dlFileEntry, dlFileVersion, keys);
1272                    }
1273            }
1274    
1275            protected void convertExtraSettings(
1276                    UnicodeProperties extraSettingsProperties, ExpandoBridge expandoBridge,
1277                    String[] keys) {
1278    
1279                    for (String key : keys) {
1280                            String value = extraSettingsProperties.remove(key);
1281    
1282                            if (Validator.isNull(value)) {
1283                                    continue;
1284                            }
1285    
1286                            int type = expandoBridge.getAttributeType(key);
1287    
1288                            Serializable serializable = ExpandoColumnConstants.getSerializable(
1289                                    type, value);
1290    
1291                            expandoBridge.setAttribute(key, serializable);
1292                    }
1293            }
1294    
1295            protected void deleteFileEntry(DLFileEntry dlFileEntry)
1296                    throws PortalException, SystemException {
1297    
1298                    // File entry
1299    
1300                    dlFileEntryPersistence.remove(dlFileEntry);
1301    
1302                    // Resources
1303    
1304                    resourceLocalService.deleteResource(
1305                            dlFileEntry.getCompanyId(), DLFileEntry.class.getName(),
1306                            ResourceConstants.SCOPE_INDIVIDUAL, dlFileEntry.getFileEntryId());
1307    
1308                    // WebDAVProps
1309    
1310                    webDAVPropsLocalService.deleteWebDAVProps(
1311                            DLFileEntry.class.getName(), dlFileEntry.getFileEntryId());
1312    
1313                    // File entry metadata
1314    
1315                    dlFileEntryMetadataLocalService.deleteFileEntryMetadata(
1316                            dlFileEntry.getFileEntryId());
1317    
1318                    // File versions
1319    
1320                    List<DLFileVersion> dlFileVersions =
1321                            dlFileVersionPersistence.findByFileEntryId(
1322                                    dlFileEntry.getFileEntryId());
1323    
1324                    for (DLFileVersion dlFileVersion : dlFileVersions) {
1325                            dlFileVersionPersistence.remove(dlFileVersion);
1326    
1327                            expandoValueLocalService.deleteValues(
1328                                    DLFileVersion.class.getName(),
1329                                    dlFileVersion.getFileVersionId());
1330    
1331                            workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1332                                    dlFileEntry.getCompanyId(), dlFileEntry.getGroupId(),
1333                                    DLFileEntry.class.getName(), dlFileVersion.getFileVersionId());
1334                    }
1335    
1336                    // Expando
1337    
1338                    expandoValueLocalService.deleteValues(
1339                            DLFileEntry.class.getName(), dlFileEntry.getFileEntryId());
1340    
1341                    // Lock
1342    
1343                    lockLocalService.unlock(
1344                            DLFileEntry.class.getName(), dlFileEntry.getFileEntryId());
1345    
1346                    // File
1347    
1348                    try {
1349                            DLStoreUtil.deleteFile(
1350                                    dlFileEntry.getCompanyId(), dlFileEntry.getDataRepositoryId(),
1351                                    dlFileEntry.getName());
1352                    }
1353                    catch (Exception e) {
1354                            if (_log.isWarnEnabled()) {
1355                                    _log.warn(e, e);
1356                            }
1357                    }
1358    
1359                    // Index
1360    
1361                    Indexer indexer = IndexerRegistryUtil.getIndexer(DLFileEntry.class);
1362    
1363                    indexer.delete(dlFileEntry);
1364            }
1365    
1366            protected String getExtension(String title, String sourceFileName) {
1367                    String extension = FileUtil.getExtension(sourceFileName);
1368    
1369                    if (Validator.isNull(extension)) {
1370                            extension = FileUtil.getExtension(title);
1371                    }
1372    
1373                    return extension;
1374            }
1375    
1376            protected Long getFileEntryTypeId(
1377                            long[] groupIds, long folderId, long fileEntryTypeId)
1378                    throws PortalException, SystemException {
1379    
1380                    if (fileEntryTypeId == -1) {
1381                            fileEntryTypeId =
1382                                    dlFileEntryTypeLocalService.getDefaultFileEntryTypeId(folderId);
1383                    }
1384                    else {
1385                            List<DLFileEntryType> dlFileEntryTypes =
1386                                    dlFileEntryTypeLocalService.getFolderFileEntryTypes(
1387                                            groupIds, folderId, true);
1388    
1389                            boolean found = false;
1390    
1391                            for (DLFileEntryType dlFileEntryType : dlFileEntryTypes) {
1392                                    if (dlFileEntryType.getFileEntryTypeId() == fileEntryTypeId) {
1393                                            found = true;
1394    
1395                                            break;
1396                                    }
1397                            }
1398    
1399                            if (!found) {
1400                                    throw new InvalidFileEntryTypeException(
1401                                            "Invalid file entry type " + fileEntryTypeId +
1402                                                    " for folder " + folderId);
1403                            }
1404                    }
1405    
1406                    return fileEntryTypeId;
1407            }
1408    
1409            protected String getNextVersion(
1410                            DLFileEntry dlFileEntry, boolean majorVersion, int workflowAction)
1411                    throws PortalException, SystemException {
1412    
1413                    String version = dlFileEntry.getVersion();
1414    
1415                    try {
1416                            DLFileVersion dlFileVersion =
1417                                    dlFileVersionLocalService.getLatestFileVersion(
1418                                            dlFileEntry.getFileEntryId(), true);
1419    
1420                            version = dlFileVersion.getVersion();
1421                    }
1422                    catch (NoSuchFileVersionException nsfve) {
1423                    }
1424    
1425                    if (workflowAction == WorkflowConstants.ACTION_SAVE_DRAFT) {
1426                            majorVersion = false;
1427                    }
1428    
1429                    int[] versionParts = StringUtil.split(version, StringPool.PERIOD, 0);
1430    
1431                    if (majorVersion) {
1432                            versionParts[0]++;
1433                            versionParts[1] = 0;
1434                    }
1435                    else {
1436                            versionParts[1]++;
1437                    }
1438    
1439                    return versionParts[0] + StringPool.PERIOD + versionParts[1];
1440            }
1441    
1442            protected DLFileEntry moveFileEntryImpl(
1443                            long userId, long fileEntryId, long newFolderId,
1444                            ServiceContext serviceContext)
1445                    throws PortalException, SystemException {
1446    
1447                    // File entry
1448    
1449                    User user = userPersistence.findByPrimaryKey(userId);
1450                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
1451                            fileEntryId);
1452    
1453                    long oldDataRepositoryId = dlFileEntry.getDataRepositoryId();
1454    
1455                    validateFile(
1456                            dlFileEntry.getGroupId(), newFolderId, dlFileEntry.getFileEntryId(),
1457                            dlFileEntry.getTitle(), dlFileEntry.getExtension());
1458    
1459                    if (DLStoreUtil.hasFile(
1460                                    user.getCompanyId(),
1461                                    DLFolderConstants.getDataRepositoryId(
1462                                            dlFileEntry.getGroupId(), newFolderId),
1463                                    dlFileEntry.getName(), StringPool.BLANK)) {
1464    
1465                            throw new DuplicateFileException(dlFileEntry.getName());
1466                    }
1467    
1468                    dlFileEntry.setFolderId(newFolderId);
1469    
1470                    dlFileEntryPersistence.update(dlFileEntry, false);
1471    
1472                    // File version
1473    
1474                    List<DLFileVersion> dlFileVersions =
1475                            dlFileVersionPersistence.findByFileEntryId(fileEntryId);
1476    
1477                    for (DLFileVersion dlFileVersion : dlFileVersions) {
1478                            dlFileVersion.setFolderId(newFolderId);
1479    
1480                            dlFileVersionPersistence.update(dlFileVersion, false);
1481                    }
1482    
1483                    // File
1484    
1485                    DLStoreUtil.updateFile(
1486                            user.getCompanyId(), oldDataRepositoryId,
1487                            dlFileEntry.getDataRepositoryId(), dlFileEntry.getName());
1488    
1489                    // Index
1490    
1491                    reindex(dlFileEntry);
1492    
1493                    return dlFileEntry;
1494            }
1495    
1496            protected void reindex(DLFileEntry dlFileEntry) throws SearchException {
1497                    Indexer indexer = IndexerRegistryUtil.getIndexer(DLFileEntry.class);
1498    
1499                    indexer.reindex(dlFileEntry);
1500            }
1501    
1502            protected void startWorkflowInstance(
1503                            long userId, ServiceContext serviceContext,
1504                            DLFileVersion dlFileVersion, String syncEventType)
1505                    throws PortalException, SystemException {
1506    
1507                    Map<String, Serializable> workflowContext =
1508                            new HashMap<String, Serializable>();
1509    
1510                    workflowContext.put("event", syncEventType);
1511    
1512                    WorkflowHandlerRegistryUtil.startWorkflowInstance(
1513                            dlFileVersion.getCompanyId(), dlFileVersion.getGroupId(), userId,
1514                            DLFileEntry.class.getName(), dlFileVersion.getFileVersionId(),
1515                            dlFileVersion, serviceContext, workflowContext);
1516            }
1517    
1518            protected DLFileEntry updateFileEntry(
1519                            long userId, long fileEntryId, String sourceFileName,
1520                            String extension, String mimeType, String title, String description,
1521                            String changeLog, boolean majorVersion, String extraSettings,
1522                            long fileEntryTypeId, Map<String, Fields> fieldsMap, File file,
1523                            InputStream is, long size, ServiceContext serviceContext)
1524                    throws PortalException, SystemException {
1525    
1526                    User user = userPersistence.findByPrimaryKey(userId);
1527                    DLFileEntry dlFileEntry = dlFileEntryPersistence.findByPrimaryKey(
1528                            fileEntryId);
1529    
1530                    boolean checkedOut = dlFileEntry.isCheckedOut();
1531    
1532                    DLFileVersion dlFileVersion =
1533                            dlFileVersionLocalService.getLatestFileVersion(
1534                                    fileEntryId, !checkedOut);
1535    
1536                    boolean autoCheckIn = !checkedOut && dlFileVersion.isApproved();
1537    
1538                    if (autoCheckIn) {
1539                            dlFileEntry = checkOutFileEntry(
1540                                    userId, fileEntryId, serviceContext);
1541                    }
1542                    else if (!checkedOut) {
1543                            lockFileEntry(userId, fileEntryId);
1544                    }
1545    
1546                    if (!hasFileEntryLock(userId, fileEntryId)) {
1547                            lockFileEntry(userId, fileEntryId);
1548                    }
1549    
1550                    if (checkedOut || autoCheckIn) {
1551                            dlFileVersion = dlFileVersionLocalService.getLatestFileVersion(
1552                                    fileEntryId, false);
1553                    }
1554    
1555                    try {
1556                            if (Validator.isNull(extension)) {
1557                                    extension = dlFileEntry.getExtension();
1558                            }
1559    
1560                            if (Validator.isNull(mimeType)) {
1561                                    mimeType = dlFileEntry.getMimeType();
1562                            }
1563    
1564                            if (Validator.isNull(title)) {
1565                                    title = sourceFileName;
1566    
1567                                    if (Validator.isNull(title)) {
1568                                            title = dlFileEntry.getTitle();
1569                                    }
1570                            }
1571    
1572                            Date now = new Date();
1573    
1574                            validateFile(
1575                                    dlFileEntry.getGroupId(), dlFileEntry.getFolderId(),
1576                                    dlFileEntry.getFileEntryId(), title, extension, sourceFileName,
1577                                    file, is);
1578    
1579                            // File version
1580    
1581                            String version = dlFileVersion.getVersion();
1582    
1583                            if (size == 0) {
1584                                    size = dlFileVersion.getSize();
1585                            }
1586    
1587                            updateFileVersion(
1588                                    user, dlFileVersion, sourceFileName, extension, mimeType, title,
1589                                    description, changeLog, extraSettings, fileEntryTypeId,
1590                                    fieldsMap, version, size, dlFileVersion.getStatus(),
1591                                    serviceContext.getModifiedDate(now), serviceContext);
1592    
1593                            // App helper
1594    
1595                            dlAppHelperLocalService.updateAsset(
1596                                    userId, new LiferayFileEntry(dlFileEntry),
1597                                    new LiferayFileVersion(dlFileVersion),
1598                                    serviceContext.getAssetCategoryIds(),
1599                                    serviceContext.getAssetTagNames(),
1600                                    serviceContext.getAssetLinkEntryIds());
1601    
1602                            // File
1603    
1604                            if ((file != null) || (is != null)) {
1605                                    try {
1606                                            DLStoreUtil.deleteFile(
1607                                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
1608                                                    dlFileEntry.getName(), version);
1609                                    }
1610                                    catch (NoSuchModelException nsme) {
1611                                    }
1612    
1613                                    if (file != null) {
1614                                            DLStoreUtil.updateFile(
1615                                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
1616                                                    dlFileEntry.getName(), dlFileEntry.getExtension(),
1617                                                    false, version, sourceFileName, file);
1618                                    }
1619                                    else {
1620                                            DLStoreUtil.updateFile(
1621                                                    user.getCompanyId(), dlFileEntry.getDataRepositoryId(),
1622                                                    dlFileEntry.getName(), dlFileEntry.getExtension(),
1623                                                    false, version, sourceFileName, is);
1624                                    }
1625                            }
1626    
1627                            if (autoCheckIn) {
1628                                    checkInFileEntry(
1629                                            userId, fileEntryId, majorVersion, changeLog,
1630                                            serviceContext);
1631                            }
1632                            else if (!checkedOut &&
1633                                             (serviceContext.getWorkflowAction() ==
1634                                                    WorkflowConstants.ACTION_PUBLISH)) {
1635    
1636                                    String syncEvent = DLSyncConstants.EVENT_UPDATE;
1637    
1638                                    if (dlFileVersion.getVersion().equals(
1639                                                    DLFileEntryConstants.VERSION_DEFAULT)) {
1640    
1641                                            syncEvent = DLSyncConstants.EVENT_ADD;
1642                                    }
1643    
1644                                    startWorkflowInstance(
1645                                            userId, serviceContext, dlFileVersion, syncEvent);
1646                            }
1647                    }
1648                    catch (PortalException pe) {
1649                            if (autoCheckIn) {
1650                                    cancelCheckOut(userId, fileEntryId);
1651                            }
1652    
1653                            throw pe;
1654                    }
1655                    catch (SystemException se) {
1656                            if (autoCheckIn) {
1657                                    cancelCheckOut(userId, fileEntryId);
1658                            }
1659    
1660                            throw se;
1661                    }
1662                    finally {
1663                            if (!autoCheckIn && !checkedOut) {
1664                                    unlockFileEntry(fileEntryId);
1665                            }
1666                    }
1667    
1668                    return dlFileEntryPersistence.findByPrimaryKey(fileEntryId);
1669            }
1670    
1671            protected DLFileVersion updateFileVersion(
1672                            User user, DLFileVersion dlFileVersion, String sourceFileName,
1673                            String extension, String mimeType, String title, String description,
1674                            String changeLog, String extraSettings, long fileEntryTypeId,
1675                            Map<String, Fields> fieldsMap, String version, long size,
1676                            int status, Date statusDate, ServiceContext serviceContext)
1677                    throws PortalException, SystemException {
1678    
1679                    dlFileVersion.setModifiedDate(statusDate);
1680    
1681                    if (Validator.isNotNull(sourceFileName)) {
1682                            dlFileVersion.setExtension(extension);
1683                            dlFileVersion.setMimeType(mimeType);
1684                    }
1685    
1686                    dlFileVersion.setTitle(title);
1687                    dlFileVersion.setDescription(description);
1688                    dlFileVersion.setChangeLog(changeLog);
1689                    dlFileVersion.setExtraSettings(extraSettings);
1690                    dlFileVersion.setFileEntryTypeId(fileEntryTypeId);
1691                    dlFileVersion.setVersion(version);
1692                    dlFileVersion.setSize(size);
1693                    dlFileVersion.setStatus(status);
1694                    dlFileVersion.setStatusByUserId(user.getUserId());
1695                    dlFileVersion.setStatusByUserName(user.getFullName());
1696                    dlFileVersion.setStatusDate(statusDate);
1697                    dlFileVersion.setExpandoBridgeAttributes(serviceContext);
1698    
1699                    dlFileVersion = dlFileVersionPersistence.update(dlFileVersion, false);
1700    
1701                    if ((fileEntryTypeId > 0) && (fieldsMap != null)) {
1702                            dlFileEntryMetadataLocalService.updateFileEntryMetadata(
1703                                    fileEntryTypeId, dlFileVersion.getFileEntryId(),
1704                                    dlFileVersion.getFileVersionId(), fieldsMap, serviceContext);
1705                    }
1706    
1707                    return dlFileVersion;
1708            }
1709    
1710            protected void validateFile(
1711                            long groupId, long folderId, long fileEntryId, String title,
1712                            String extension)
1713                    throws PortalException, SystemException {
1714    
1715                    DLFolder dlFolder = dlFolderPersistence.fetchByG_P_N(
1716                            groupId, folderId, title);
1717    
1718                    if (dlFolder != null) {
1719                            throw new DuplicateFolderNameException(title);
1720                    }
1721    
1722                    DLFileEntry dlFileEntry = dlFileEntryPersistence.fetchByG_F_T(
1723                            groupId, folderId, title);
1724    
1725                    if ((dlFileEntry != null) &&
1726                            (dlFileEntry.getFileEntryId() != fileEntryId)) {
1727    
1728                            throw new DuplicateFileException(title);
1729                    }
1730    
1731                    String periodAndExtension = StringPool.PERIOD + extension;
1732    
1733                    if (!title.endsWith(periodAndExtension)) {
1734                            title += periodAndExtension;
1735    
1736                            dlFileEntry = dlFileEntryPersistence.fetchByG_F_T(
1737                                    groupId, folderId, title);
1738    
1739                            if ((dlFileEntry != null) &&
1740                                    (dlFileEntry.getFileEntryId() != fileEntryId)) {
1741    
1742                                    throw new DuplicateFileException(title);
1743                            }
1744                    }
1745            }
1746    
1747            protected void validateFile(
1748                            long groupId, long folderId, long fileEntryId, String title,
1749                            String extension, String sourceFileName, File file, InputStream is)
1750                    throws PortalException, SystemException {
1751    
1752                    if (Validator.isNotNull(sourceFileName)) {
1753                            if (file != null) {
1754                                    DLStoreUtil.validate(
1755                                            sourceFileName, extension, sourceFileName, true, file);
1756                            }
1757                            else {
1758                                    DLStoreUtil.validate(
1759                                            sourceFileName, extension, sourceFileName, true, is);
1760                            }
1761                    }
1762    
1763                    validateFileName(title);
1764    
1765                    DLStoreUtil.validate(title, false);
1766    
1767                    validateFile(groupId, folderId, fileEntryId, title, extension);
1768            }
1769    
1770            protected void validateFile(
1771                            long groupId, long folderId, String title, String extension,
1772                            File file, InputStream is)
1773                    throws PortalException, SystemException {
1774    
1775                    String fileName = title;
1776    
1777                    validateFileName(fileName);
1778    
1779                    if (file != null) {
1780                            DLStoreUtil.validate(fileName, true, file);
1781                    }
1782                    else {
1783                            DLStoreUtil.validate(fileName, true, is);
1784                    }
1785    
1786                    validateFile(groupId, folderId, 0, title, extension);
1787            }
1788    
1789            protected void validateFileName(String fileName) throws PortalException {
1790                    if (fileName.contains(StringPool.SLASH)) {
1791                            throw new FileNameException(fileName);
1792                    }
1793            }
1794    
1795            private static final int _DELETE_INTERVAL = 100;
1796    
1797            private static Log _log = LogFactoryUtil.getLog(
1798                    DLFileEntryLocalServiceImpl.class);
1799    
1800    }