1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portlet.documentlibrary.service.impl;
24  
25  import com.liferay.documentlibrary.DuplicateFileException;
26  import com.liferay.documentlibrary.FileSizeException;
27  import com.liferay.documentlibrary.NoSuchFileException;
28  import com.liferay.portal.PortalException;
29  import com.liferay.portal.SystemException;
30  import com.liferay.portal.kernel.util.FileUtil;
31  import com.liferay.portal.kernel.util.GetterUtil;
32  import com.liferay.portal.kernel.util.MimeTypesUtil;
33  import com.liferay.portal.kernel.util.OrderByComparator;
34  import com.liferay.portal.kernel.util.StringPool;
35  import com.liferay.portal.kernel.util.Validator;
36  import com.liferay.portal.model.ResourceConstants;
37  import com.liferay.portal.model.User;
38  import com.liferay.portal.util.PortalUtil;
39  import com.liferay.portal.util.PortletKeys;
40  import com.liferay.portal.util.PropsValues;
41  import com.liferay.portlet.documentlibrary.DuplicateFolderNameException;
42  import com.liferay.portlet.documentlibrary.NoSuchFileEntryException;
43  import com.liferay.portlet.documentlibrary.NoSuchFolderException;
44  import com.liferay.portlet.documentlibrary.model.DLFileEntry;
45  import com.liferay.portlet.documentlibrary.model.DLFileVersion;
46  import com.liferay.portlet.documentlibrary.model.DLFolder;
47  import com.liferay.portlet.documentlibrary.model.impl.DLFileEntryImpl;
48  import com.liferay.portlet.documentlibrary.model.impl.DLFolderImpl;
49  import com.liferay.portlet.documentlibrary.service.base.DLFileEntryLocalServiceBaseImpl;
50  import com.liferay.portlet.messageboards.model.MBDiscussion;
51  import com.liferay.util.MathUtil;
52  
53  import java.io.BufferedInputStream;
54  import java.io.ByteArrayInputStream;
55  import java.io.File;
56  import java.io.FileInputStream;
57  import java.io.FileNotFoundException;
58  import java.io.IOException;
59  import java.io.InputStream;
60  
61  import java.rmi.RemoteException;
62  
63  import java.util.ArrayList;
64  import java.util.Date;
65  import java.util.List;
66  
67  import org.apache.commons.logging.Log;
68  import org.apache.commons.logging.LogFactory;
69  
70  /**
71   * <a href="DLFileEntryLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
72   *
73   * <p>
74   * For DLFileEntries, the naming convention for some of the variables is not
75   * very informative, due to legacy code. Each DLFileEntry has a corresponding
76   * name and title. The "name" is a unique identifier for a given file and
77   * usually follows the format "DLFE-1234.xls" whereas the "title" is the actual
78   * name specified by the user (e.g., "Budget.xls").
79   * </p>
80   *
81   * @author Brian Wing Shun Chan
82   * @author Harry Mark
83   *
84   */
85  public class DLFileEntryLocalServiceImpl
86      extends DLFileEntryLocalServiceBaseImpl {
87  
88      public DLFileEntry addFileEntry(
89              long userId, long folderId, String name, String title,
90              String description, String[] tagsEntries, String extraSettings,
91              File file, boolean addCommunityPermissions,
92              boolean addGuestPermissions)
93          throws PortalException, SystemException {
94  
95          return addFileEntry(
96              userId, folderId, name, title, description, tagsEntries,
97              extraSettings, file, Boolean.valueOf(addCommunityPermissions),
98              Boolean.valueOf(addGuestPermissions), null, null);
99      }
100 
101     public DLFileEntry addFileEntry(
102             long userId, long folderId, String name, String title,
103             String description, String[] tagsEntries, String extraSettings,
104             byte[] bytes, boolean addCommunityPermissions,
105             boolean addGuestPermissions)
106         throws PortalException, SystemException {
107 
108         return addFileEntry(
109             null, userId, folderId, name, title, description, tagsEntries,
110             extraSettings, bytes, Boolean.valueOf(addCommunityPermissions),
111             Boolean.valueOf(addGuestPermissions), null, null);
112     }
113 
114     public DLFileEntry addFileEntry(
115             String uuid, long userId, long folderId, String name, String title,
116             String description, String[] tagsEntries, String extraSettings,
117             byte[] bytes, boolean addCommunityPermissions,
118             boolean addGuestPermissions)
119         throws PortalException, SystemException {
120 
121         return addFileEntry(
122             uuid, userId, folderId, name, title, description, tagsEntries,
123             extraSettings, bytes, Boolean.valueOf(addCommunityPermissions),
124             Boolean.valueOf(addGuestPermissions), null, null);
125     }
126 
127     public DLFileEntry addFileEntry(
128             long userId, long folderId, String name, String title,
129             String description, String[] tagsEntries, String extraSettings,
130             File file, String[] communityPermissions, String[] guestPermissions)
131         throws PortalException, SystemException {
132 
133         return addFileEntry(
134             userId, folderId, name, title, description, tagsEntries,
135             extraSettings, file, null, null, communityPermissions,
136             guestPermissions);
137     }
138 
139     public DLFileEntry addFileEntry(
140             long userId, long folderId, String name, String title,
141             String description, String[] tagsEntries, String extraSettings,
142             byte[] bytes, String[] communityPermissions,
143             String[] guestPermissions)
144         throws PortalException, SystemException {
145 
146         return addFileEntry(
147             null, userId, folderId, name, title, description, tagsEntries,
148             extraSettings, bytes, null, null, communityPermissions,
149             guestPermissions);
150     }
151 
152     public DLFileEntry addFileEntry(
153             long userId, long folderId, String name, String title,
154             String description, String[] tagsEntries, String extraSettings,
155             File file, Boolean addCommunityPermissions,
156             Boolean addGuestPermissions, String[] communityPermissions,
157             String[] guestPermissions)
158         throws PortalException, SystemException {
159 
160         if (!PropsValues.WEBDAV_LITMUS) {
161             if ((file == null) || (file.length() == 0)) {
162                 throw new FileSizeException();
163             }
164         }
165 
166         InputStream is = null;
167 
168         try {
169             is = new BufferedInputStream(new FileInputStream(file));
170 
171             return addFileEntry(
172                 null, userId, folderId, name, title, description, tagsEntries,
173                 extraSettings, is, file.length(), addCommunityPermissions,
174                 addGuestPermissions, communityPermissions, guestPermissions);
175         }
176         catch (FileNotFoundException fnfe) {
177             throw new FileSizeException();
178         }
179         finally {
180             try {
181                 if (is != null) {
182                     is.close();
183                 }
184             }
185             catch (IOException ioe) {
186                 _log.error(ioe);
187             }
188         }
189     }
190 
191     public DLFileEntry addFileEntry(
192             String uuid, long userId, long folderId, String name, String title,
193             String description, String[] tagsEntries, String extraSettings,
194             byte[] bytes, Boolean addCommunityPermissions,
195             Boolean addGuestPermissions, String[] communityPermissions,
196             String[] guestPermissions)
197         throws PortalException, SystemException {
198 
199         if (!PropsValues.WEBDAV_LITMUS) {
200             if ((bytes == null) || (bytes.length == 0)) {
201                 throw new FileSizeException();
202             }
203         }
204 
205         InputStream is = new ByteArrayInputStream(bytes);
206 
207         return addFileEntry(
208             uuid, userId, folderId, name, title, description, tagsEntries,
209             extraSettings, is, bytes.length, addCommunityPermissions,
210             addGuestPermissions, communityPermissions, guestPermissions);
211     }
212 
213     public DLFileEntry addFileEntry(
214             String uuid, long userId, long folderId, String name, String title,
215             String description, String[] tagsEntries, String extraSettings,
216             InputStream is, long size, Boolean addCommunityPermissions,
217             Boolean addGuestPermissions, String[] communityPermissions,
218             String[] guestPermissions)
219         throws PortalException, SystemException {
220 
221         // File entry
222 
223         User user = userPersistence.findByPrimaryKey(userId);
224         folderId = getFolderId(user.getCompanyId(), folderId);
225         DLFolder folder = dlFolderPersistence.findByPrimaryKey(folderId);
226         Date now = new Date();
227 
228         if (Validator.isNull(title)) {
229             title = name;
230         }
231 
232         name = getName(name);
233         title = DLFileEntryImpl.stripExtension(name, title);
234 
235         validate(folder.getGroupId(), folderId, name, title, is);
236 
237         long fileEntryId = counterLocalService.increment();
238 
239         DLFileEntry fileEntry = dlFileEntryPersistence.create(fileEntryId);
240 
241         fileEntry.setUuid(uuid);
242         fileEntry.setCompanyId(user.getCompanyId());
243         fileEntry.setUserId(user.getUserId());
244         fileEntry.setUserName(user.getFullName());
245         fileEntry.setVersionUserId(user.getUserId());
246         fileEntry.setVersionUserName(user.getFullName());
247         fileEntry.setCreateDate(now);
248         fileEntry.setModifiedDate(now);
249         fileEntry.setFolderId(folderId);
250         fileEntry.setName(name);
251         fileEntry.setTitle(title);
252         fileEntry.setDescription(description);
253         fileEntry.setVersion(DLFileEntryImpl.DEFAULT_VERSION);
254         fileEntry.setSize((int)size);
255         fileEntry.setReadCount(DLFileEntryImpl.DEFAULT_READ_COUNT);
256         fileEntry.setExtraSettings(extraSettings);
257 
258         dlFileEntryPersistence.update(fileEntry, false);
259 
260         // File
261 
262         dlLocalService.addFile(
263             user.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
264             folder.getGroupId(), folderId, name,
265             fileEntry.getLuceneProperties(), tagsEntries, is);
266 
267         // Resources
268 
269         if ((addCommunityPermissions != null) &&
270             (addGuestPermissions != null)) {
271 
272             addFileEntryResources(
273                 folder, fileEntry, addCommunityPermissions.booleanValue(),
274                 addGuestPermissions.booleanValue());
275         }
276         else {
277             addFileEntryResources(
278                 folder, fileEntry, communityPermissions, guestPermissions);
279         }
280 
281         // Tags
282 
283         updateTagsAsset(userId, fileEntry, tagsEntries);
284 
285         // Folder
286 
287         folder.setLastPostDate(fileEntry.getModifiedDate());
288 
289         dlFolderPersistence.update(folder, false);
290 
291         return fileEntry;
292     }
293 
294     public void addFileEntryResources(
295             long folderId, String name, boolean addCommunityPermissions,
296             boolean addGuestPermissions)
297         throws PortalException, SystemException {
298 
299         DLFolder folder = dlFolderPersistence.findByPrimaryKey(folderId);
300         DLFileEntry fileEntry = dlFileEntryPersistence.findByF_N(
301             folderId, name);
302 
303         addFileEntryResources(
304             folder, fileEntry, addCommunityPermissions, addGuestPermissions);
305     }
306 
307     public void addFileEntryResources(
308             DLFolder folder, DLFileEntry fileEntry,
309             boolean addCommunityPermissions, boolean addGuestPermissions)
310         throws PortalException, SystemException {
311 
312         resourceLocalService.addResources(
313             fileEntry.getCompanyId(), folder.getGroupId(),
314             fileEntry.getUserId(), DLFileEntry.class.getName(),
315             fileEntry.getFileEntryId(), false, addCommunityPermissions,
316             addGuestPermissions);
317     }
318 
319     public void addFileEntryResources(
320             long folderId, String name, String[] communityPermissions,
321             String[] guestPermissions)
322         throws PortalException, SystemException {
323 
324         DLFolder folder = dlFolderPersistence.findByPrimaryKey(folderId);
325         DLFileEntry fileEntry = dlFileEntryPersistence.findByF_N(
326             folderId, name);
327 
328         addFileEntryResources(
329             folder, fileEntry, communityPermissions, guestPermissions);
330     }
331 
332     public void addFileEntryResources(
333             DLFolder folder, DLFileEntry fileEntry,
334             String[] communityPermissions, String[] guestPermissions)
335         throws PortalException, SystemException {
336 
337         resourceLocalService.addModelResources(
338             fileEntry.getCompanyId(), folder.getGroupId(),
339             fileEntry.getUserId(), DLFileEntry.class.getName(),
340             fileEntry.getFileEntryId(), communityPermissions, guestPermissions);
341     }
342 
343     public DLFileEntry addOrOverwriteFileEntry(
344             long userId, long folderId, String name, String sourceName,
345             String title, String description, String[] tagsEntries,
346             String extraSettings, File file, boolean addCommunityPermissions,
347             boolean addGuestPermissions)
348         throws PortalException, SystemException {
349 
350         boolean update = false;
351 
352         String extension = FileUtil.getExtension(name);
353 
354         List<DLFileEntry> fileEntries = dlFileEntryPersistence.findByF_T(
355             folderId, title);
356 
357         for (DLFileEntry fileEntry : fileEntries) {
358             String curExtension = FileUtil.getExtension(fileEntry.getName());
359 
360             if (PropsValues.WEBDAV_LITMUS && Validator.isNull(extension)) {
361                 if (Validator.isNull(curExtension)) {
362                     update = true;
363 
364                     name = fileEntry.getName();
365 
366                     break;
367                 }
368             }
369             else if (extension.equals(curExtension)) {
370                 update = true;
371 
372                 break;
373             }
374         }
375 
376         if (update) {
377             return updateFileEntry(
378                 userId, folderId, folderId, name, sourceName, title,
379                 description, tagsEntries, extraSettings, file);
380         }
381         else {
382             return addFileEntry(
383                 userId, folderId, name, title, description, tagsEntries,
384                 extraSettings, file, addCommunityPermissions,
385                 addGuestPermissions);
386         }
387     }
388 
389     public void deleteFileEntries(long folderId)
390         throws PortalException, SystemException {
391 
392         List<DLFileEntry> fileEntries = dlFileEntryPersistence.findByFolderId(
393             folderId);
394 
395         for (DLFileEntry fileEntry : fileEntries) {
396             deleteFileEntry(fileEntry);
397         }
398     }
399 
400     public void deleteFileEntry(long folderId, String name)
401         throws PortalException, SystemException {
402 
403         deleteFileEntry(folderId, name, -1);
404     }
405 
406     public void deleteFileEntry(long folderId, String name, double version)
407         throws PortalException, SystemException {
408 
409         DLFileEntry fileEntry = dlFileEntryPersistence.findByF_N(
410             folderId, name);
411 
412         if (version > 0) {
413             try {
414                 dlService.deleteFile(
415                     fileEntry.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
416                     fileEntry.getFolderId(), fileEntry.getName(), version);
417             }
418             catch (Exception e) {
419                 if (_log.isWarnEnabled()) {
420                     _log.warn(e, e);
421                 }
422             }
423 
424             dlFileVersionPersistence.removeByF_N_V(folderId, name, version);
425         }
426         else {
427             deleteFileEntry(fileEntry);
428         }
429     }
430 
431     public void deleteFileEntry(DLFileEntry fileEntry)
432         throws PortalException, SystemException {
433 
434         // File
435 
436         try {
437             dlService.deleteFile(
438                 fileEntry.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
439                 fileEntry.getFolderId(), fileEntry.getName());
440         }
441         catch (Exception e) {
442             if (_log.isWarnEnabled()) {
443                 _log.warn(e, e);
444             }
445         }
446 
447         // File ranks
448 
449         dlFileRankLocalService.deleteFileRanks(
450             fileEntry.getFolderId(), fileEntry.getName());
451 
452         // File shortcuts
453 
454         dlFileShortcutLocalService.deleteFileShortcuts(
455             fileEntry.getFolderId(), fileEntry.getName());
456 
457         // File versions
458 
459         List<DLFileVersion> fileVersions = dlFileVersionPersistence.findByF_N(
460             fileEntry.getFolderId(), fileEntry.getName());
461 
462         for (DLFileVersion fileVersion : fileVersions) {
463             dlFileVersionPersistence.remove(fileVersion);
464         }
465 
466         // Tags
467 
468         tagsAssetLocalService.deleteAsset(
469             DLFileEntry.class.getName(), fileEntry.getFileEntryId());
470 
471         // Ratings
472 
473         ratingsStatsLocalService.deleteStats(
474             DLFileEntry.class.getName(), fileEntry.getFileEntryId());
475 
476         // Message boards
477 
478         mbMessageLocalService.deleteDiscussionMessages(
479             DLFileEntry.class.getName(), fileEntry.getFileEntryId());
480 
481         // WebDAVProps
482 
483         webDAVPropsLocalService.deleteWebDAVProps(
484             DLFileEntry.class.getName(), fileEntry.getPrimaryKey());
485 
486         // Resources
487 
488         resourceLocalService.deleteResource(
489             fileEntry.getCompanyId(), DLFileEntry.class.getName(),
490             ResourceConstants.SCOPE_INDIVIDUAL, fileEntry.getFileEntryId());
491 
492         // File entry
493 
494         dlFileEntryPersistence.remove(fileEntry);
495     }
496 
497     public List<DLFileEntry> getCompanyFileEntries(
498             long companyId, int start, int end)
499         throws SystemException {
500 
501         return dlFileEntryPersistence.findByCompanyId(companyId, start, end);
502     }
503 
504     public List<DLFileEntry> getCompanyFileEntries(
505             long companyId, int start, int end, OrderByComparator obc)
506         throws SystemException {
507 
508         return dlFileEntryPersistence.findByCompanyId(
509             companyId, start, end, obc);
510     }
511 
512     public int getCompanyFileEntriesCount(long companyId)
513         throws SystemException {
514 
515         return dlFileEntryPersistence.countByCompanyId(companyId);
516     }
517 
518     public InputStream getFileAsStream(
519             long companyId, long userId, long folderId, String name)
520         throws PortalException, SystemException {
521 
522         return getFileAsStream(companyId, userId, folderId, name, 0);
523     }
524 
525     public InputStream getFileAsStream(
526             long companyId, long userId, long folderId, String name,
527             double version)
528         throws PortalException, SystemException {
529 
530         if (userId > 0) {
531             DLFolder folder = dlFolderPersistence.findByPrimaryKey(folderId);
532 
533             dlFileRankLocalService.updateFileRank(
534                 folder.getGroupId(), companyId, userId, folderId, name);
535         }
536 
537         DLFileEntry fileEntry = dlFileEntryPersistence.findByF_N(
538             folderId, name);
539 
540         fileEntry.setReadCount(fileEntry.getReadCount() + 1);
541 
542         dlFileEntryPersistence.update(fileEntry, false);
543 
544         if ((version > 0) && (fileEntry.getVersion() != version)) {
545             return dlLocalService.getFileAsStream(
546                 companyId, folderId, name, version);
547         }
548         else {
549             return dlLocalService.getFileAsStream(companyId, folderId, name);
550         }
551     }
552 
553     public List<DLFileEntry> getFileEntries(long folderId)
554         throws SystemException {
555 
556         return dlFileEntryPersistence.findByFolderId(folderId);
557     }
558 
559     public List<DLFileEntry> getFileEntries(long folderId, int start, int end)
560         throws SystemException {
561 
562         return dlFileEntryPersistence.findByFolderId(folderId, start, end);
563     }
564 
565     public List<DLFileEntry> getFileEntries(
566             long folderId, int start, int end, OrderByComparator obc)
567         throws SystemException {
568 
569         return dlFileEntryPersistence.findByFolderId(folderId, start, end, obc);
570     }
571 
572     public List<Object> getFileEntriesAndShortcuts(
573             long folderId, int start, int end)
574         throws SystemException {
575 
576         List<Long> folderIds = new ArrayList<Long>();
577 
578         folderIds.add(folderId);
579 
580         return dlFileEntryAndShortcutFinder.findByFolderIds(
581             folderIds, start, end);
582     }
583 
584     public List<Object> getFileEntriesAndShortcuts(
585             List<Long> folderIds, int start, int end)
586         throws SystemException {
587 
588         return dlFileEntryAndShortcutFinder.findByFolderIds(
589             folderIds, start, end);
590     }
591 
592     public int getFileEntriesAndShortcutsCount(long folderId)
593         throws SystemException {
594 
595         List<Long> folderIds = new ArrayList<Long>();
596 
597         folderIds.add(folderId);
598 
599         return dlFileEntryAndShortcutFinder.countByFolderIds(folderIds);
600     }
601 
602     public int getFileEntriesAndShortcutsCount(List<Long> folderIds)
603         throws SystemException {
604 
605         return dlFileEntryAndShortcutFinder.countByFolderIds(folderIds);
606     }
607 
608     public int getFileEntriesCount(long folderId) throws SystemException {
609         return dlFileEntryPersistence.countByFolderId(folderId);
610     }
611 
612     public DLFileEntry getFileEntry(long fileEntryId)
613         throws PortalException, SystemException {
614 
615         return dlFileEntryPersistence.findByPrimaryKey(fileEntryId);
616     }
617 
618     public DLFileEntry getFileEntry(long folderId, String name)
619         throws PortalException, SystemException {
620 
621         return dlFileEntryPersistence.findByF_N(folderId, name);
622     }
623 
624     public DLFileEntry getFileEntryByUuidAndGroupId(String uuid, long groupId)
625         throws PortalException, SystemException {
626 
627         return dlFileEntryFinder.findByUuid_G(uuid, groupId);
628     }
629 
630     public DLFileEntry getFileEntryByTitle(
631             long folderId, String titleWithExtension)
632         throws PortalException, SystemException {
633 
634         String title = DLFileEntryImpl.stripExtension(
635             titleWithExtension, titleWithExtension);
636         String extension = FileUtil.getExtension(titleWithExtension);
637 
638         List<DLFileEntry> fileEntries = dlFileEntryPersistence.findByF_T(
639             folderId, title);
640 
641         for (DLFileEntry fileEntry : fileEntries) {
642             String curExtension = FileUtil.getExtension(fileEntry.getName());
643 
644             if (PropsValues.WEBDAV_LITMUS && Validator.isNull(extension)) {
645                 if (Validator.isNull(curExtension)) {
646                     return fileEntry;
647                 }
648             }
649             else if (extension.equals(curExtension)) {
650                 return fileEntry;
651             }
652         }
653 
654         throw new NoSuchFileEntryException();
655     }
656 
657     public int getFoldersFileEntriesCount(List<Long> folderIds)
658         throws SystemException {
659 
660         return dlFileEntryFinder.countByFolderIds(folderIds);
661     }
662 
663     public List<DLFileEntry> getGroupFileEntries(
664             long groupId, int start, int end)
665         throws SystemException {
666 
667         return dlFileEntryFinder.findByGroupId(groupId, start, end);
668     }
669 
670     public List<DLFileEntry> getGroupFileEntries(
671             long groupId, int start, int end, OrderByComparator obc)
672         throws SystemException {
673 
674         return dlFileEntryFinder.findByGroupId(groupId, start, end, obc);
675     }
676 
677     public List<DLFileEntry> getGroupFileEntries(
678             long groupId, long userId, int start, int end)
679         throws SystemException {
680 
681         if (userId <= 0) {
682             return dlFileEntryFinder.findByGroupId(groupId, start, end);
683         }
684         else {
685             return dlFileEntryFinder.findByG_U(groupId, userId, start, end);
686         }
687     }
688 
689     public List<DLFileEntry> getGroupFileEntries(
690             long groupId, long userId, int start, int end,
691             OrderByComparator obc)
692         throws SystemException {
693 
694         if (userId <= 0) {
695             return dlFileEntryFinder.findByGroupId(groupId, start, end, obc);
696         }
697         else {
698             return dlFileEntryFinder.findByG_U(
699                 groupId, userId, start, end, obc);
700         }
701     }
702 
703     public int getGroupFileEntriesCount(long groupId) throws SystemException {
704         return dlFileEntryFinder.countByGroupId(groupId);
705     }
706 
707     public int getGroupFileEntriesCount(long groupId, long userId)
708         throws SystemException {
709 
710         if (userId <= 0) {
711             return dlFileEntryFinder.countByGroupId(groupId);
712         }
713         else {
714             return dlFileEntryFinder.countByG_U(groupId, userId);
715         }
716     }
717 
718     public List<DLFileEntry> getNoAssetFileEntries() throws SystemException {
719         return dlFileEntryFinder.findByNoAssets();
720     }
721 
722     public DLFileEntry updateFileEntry(
723             long userId, long folderId, long newFolderId, String name,
724             String sourceFileName, String title, String description,
725             String[] tagsEntries, String extraSettings, File file)
726         throws PortalException, SystemException {
727 
728         InputStream is = null;
729 
730         try {
731             long size = 0;
732 
733             if ((file != null) && (file.length() > 0)) {
734                 is = new BufferedInputStream(new FileInputStream(file));
735                 size = file.length();
736             }
737 
738             return updateFileEntry(
739                 userId, folderId, newFolderId, name, sourceFileName, title,
740                 description, tagsEntries, extraSettings, is, size);
741         }
742         catch (FileNotFoundException fnfe) {
743             throw new NoSuchFileException();
744         }
745         finally {
746             try {
747                 if (is != null) {
748                     is.close();
749                 }
750             }
751             catch (IOException ioe) {
752                 _log.error(ioe);
753             }
754         }
755     }
756 
757     public DLFileEntry updateFileEntry(
758             long userId, long folderId, long newFolderId, String name,
759             String sourceFileName, String title, String description,
760             String[] tagsEntries, String extraSettings, byte[] bytes)
761         throws PortalException, SystemException {
762 
763         InputStream is = null;
764         long size = 0;
765 
766         if ((bytes != null) && (bytes.length > 0)) {
767             is = new ByteArrayInputStream(bytes);
768             size = bytes.length;
769         }
770 
771         return updateFileEntry(
772             userId, folderId, newFolderId, name, sourceFileName, title,
773             description, tagsEntries, extraSettings, is, size);
774     }
775 
776     public DLFileEntry updateFileEntry(
777             long userId, long folderId, long newFolderId, String name,
778             String sourceFileName, String title, String description,
779             String[] tagsEntries, String extraSettings, InputStream is,
780             long size)
781         throws PortalException, SystemException {
782 
783         // File entry
784 
785         User user = userPersistence.findByPrimaryKey(userId);
786         DLFolder folder = dlFolderPersistence.findByPrimaryKey(folderId);
787 
788         if (Validator.isNull(title)) {
789             title = sourceFileName;
790 
791             if (Validator.isNull(title)) {
792                 title = name;
793             }
794         }
795 
796         title = DLFileEntryImpl.stripExtension(name, title);
797 
798         validate(
799             folder.getGroupId(), folderId, newFolderId, name, title,
800             sourceFileName, is);
801 
802         DLFileEntry fileEntry = dlFileEntryPersistence.findByF_N(
803             folderId, name);
804 
805         fileEntry.setTitle(title);
806         fileEntry.setDescription(description);
807         fileEntry.setExtraSettings(extraSettings);
808 
809         dlFileEntryPersistence.update(fileEntry, false);
810 
811         // Move file entry
812 
813         if ((newFolderId > 0) && (folderId != newFolderId)) {
814             long oldFileEntryId = fileEntry.getFileEntryId();
815 
816             DLFolder newFolder = dlFolderPersistence.findByPrimaryKey(
817                 newFolderId);
818 
819             if (folder.getGroupId() != newFolder.getGroupId()) {
820                 throw new NoSuchFolderException();
821             }
822 
823             if (dlLocalService.hasFile(
824                     user.getCompanyId(), newFolderId, name, 0)) {
825 
826                 throw new DuplicateFileException(name);
827             }
828 
829             long newFileEntryId = counterLocalService.increment();
830 
831             DLFileEntry newFileEntry = dlFileEntryPersistence.create(
832                 newFileEntryId);
833 
834             newFileEntry.setCompanyId(fileEntry.getCompanyId());
835             newFileEntry.setUserId(fileEntry.getUserId());
836             newFileEntry.setUserName(fileEntry.getUserName());
837             newFileEntry.setVersionUserId(fileEntry.getVersionUserId());
838             newFileEntry.setVersionUserName(fileEntry.getVersionUserName());
839             newFileEntry.setCreateDate(fileEntry.getCreateDate());
840             newFileEntry.setModifiedDate(fileEntry.getModifiedDate());
841             newFileEntry.setFolderId(newFolderId);
842             newFileEntry.setName(name);
843             newFileEntry.setTitle(fileEntry.getTitle());
844             newFileEntry.setDescription(fileEntry.getDescription());
845             newFileEntry.setVersion(fileEntry.getVersion());
846             newFileEntry.setSize(fileEntry.getSize());
847             newFileEntry.setReadCount(fileEntry.getReadCount());
848             newFileEntry.setExtraSettings(extraSettings);
849 
850             dlFileEntryPersistence.update(newFileEntry, false);
851 
852             dlFileEntryPersistence.remove(fileEntry);
853 
854             fileEntry = newFileEntry;
855 
856             List<DLFileVersion> fileVersions =
857                 dlFileVersionPersistence.findByF_N(folderId, name);
858 
859             for (DLFileVersion fileVersion : fileVersions) {
860                 long newFileVersionId = counterLocalService.increment();
861 
862                 DLFileVersion newFileVersion = dlFileVersionPersistence.create(
863                     newFileVersionId);
864 
865                 newFileVersion.setCompanyId(fileVersion.getCompanyId());
866                 newFileVersion.setUserId(fileVersion.getUserId());
867                 newFileVersion.setUserName(fileVersion.getUserName());
868                 newFileVersion.setCreateDate(fileVersion.getCreateDate());
869                 newFileVersion.setFolderId(newFolderId);
870                 newFileVersion.setName(name);
871                 newFileVersion.setVersion(fileVersion.getVersion());
872                 newFileVersion.setSize(fileVersion.getSize());
873 
874                 dlFileVersionPersistence.update(newFileVersion, false);
875 
876                 dlFileVersionPersistence.remove(fileVersion);
877             }
878 
879             dlFileShortcutLocalService.updateFileShortcuts(
880                 folderId, name, newFolderId, name);
881 
882             try {
883                 dlService.updateFile(
884                     user.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
885                     folder.getGroupId(), folderId, newFolderId, name);
886             }
887             catch (RemoteException re) {
888                 throw new SystemException(re);
889             }
890 
891             folderId = newFolderId;
892             folder = newFolder;
893 
894             // Message boards
895 
896             MBDiscussion discussion = mbDiscussionPersistence.fetchByC_C(
897                 PortalUtil.getClassNameId(DLFileEntry.class.getName()),
898                 oldFileEntryId);
899 
900             if (discussion != null) {
901                 discussion.setClassPK(newFileEntryId);
902 
903                 mbDiscussionPersistence.update(discussion, false);
904             }
905         }
906 
907         // Tags
908 
909         updateTagsAsset(userId, fileEntry, tagsEntries);
910 
911         // File version
912 
913         double oldVersion = fileEntry.getVersion();
914         double newVersion = MathUtil.format(oldVersion + 0.1, 1, 1);
915 
916         if (is == null) {
917             fileEntry.setVersion(newVersion);
918 
919             dlFileEntryPersistence.update(fileEntry, false);
920 
921             is = dlLocalService.getFileAsStream(
922                 user.getCompanyId(), folderId, name);
923 
924             dlLocalService.updateFile(
925                 user.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
926                 folder.getGroupId(), folderId, name, newVersion, name,
927                 fileEntry.getLuceneProperties(), tagsEntries, is);
928 
929             return fileEntry;
930         }
931 
932         long fileVersionId = counterLocalService.increment();
933 
934         DLFileVersion fileVersion = dlFileVersionPersistence.create(
935             fileVersionId);
936 
937         long versionUserId = fileEntry.getVersionUserId();
938 
939         if (versionUserId <= 0) {
940             versionUserId = fileEntry.getUserId();
941         }
942 
943         String versionUserName = GetterUtil.getString(
944             fileEntry.getVersionUserName(), fileEntry.getUserName());
945 
946         fileVersion.setCompanyId(fileEntry.getCompanyId());
947         fileVersion.setUserId(versionUserId);
948         fileVersion.setUserName(versionUserName);
949         fileVersion.setCreateDate(fileEntry.getModifiedDate());
950         fileVersion.setFolderId(folderId);
951         fileVersion.setName(name);
952         fileVersion.setVersion(oldVersion);
953         fileVersion.setSize(fileEntry.getSize());
954 
955         dlFileVersionPersistence.update(fileVersion, false);
956 
957         // File entry
958 
959         fileEntry.setVersionUserId(user.getUserId());
960         fileEntry.setVersionUserName(user.getFullName());
961         fileEntry.setModifiedDate(new Date());
962         fileEntry.setVersion(newVersion);
963         fileEntry.setSize((int)size);
964 
965         dlFileEntryPersistence.update(fileEntry, false);
966 
967         // File
968 
969         dlLocalService.updateFile(
970             user.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
971             folder.getGroupId(), folderId, name, newVersion, sourceFileName,
972             fileEntry.getLuceneProperties(), tagsEntries, is);
973 
974         // Folder
975 
976         folder.setLastPostDate(fileEntry.getModifiedDate());
977 
978         dlFolderPersistence.update(folder, false);
979 
980         return fileEntry;
981     }
982 
983     public void updateTagsAsset(
984             long userId, DLFileEntry fileEntry, String[] tagsEntries)
985         throws PortalException, SystemException {
986 
987         String mimeType = MimeTypesUtil.getContentType(fileEntry.getName());
988 
989         tagsAssetLocalService.updateAsset(
990             userId, fileEntry.getFolder().getGroupId(),
991             DLFileEntry.class.getName(), fileEntry.getFileEntryId(),
992             tagsEntries, null, null, null, null, mimeType, fileEntry.getTitle(),
993             fileEntry.getDescription(), null, null, 0, 0, null, false);
994     }
995 
996     protected long getFolderId(long companyId, long folderId)
997         throws SystemException {
998 
999         if (folderId != DLFolderImpl.DEFAULT_PARENT_FOLDER_ID) {
1000
1001            // Ensure folder exists and belongs to the proper company
1002
1003            DLFolder folder = dlFolderPersistence.fetchByPrimaryKey(folderId);
1004
1005            if ((folder == null) || (companyId != folder.getCompanyId())) {
1006                folderId = DLFolderImpl.DEFAULT_PARENT_FOLDER_ID;
1007            }
1008        }
1009
1010        return folderId;
1011    }
1012
1013    protected String getName(String name) throws SystemException {
1014        String extension = StringPool.BLANK;
1015
1016        int pos = name.lastIndexOf(StringPool.PERIOD);
1017
1018        if (pos != -1) {
1019            extension = name.substring(pos + 1, name.length()).toLowerCase();
1020        }
1021
1022        name = String.valueOf(counterLocalService.increment(
1023            DLFileEntry.class.getName()));
1024
1025        if (Validator.isNotNull(extension)) {
1026            name = "DLFE-" + name + StringPool.PERIOD + extension;
1027        }
1028
1029        return name;
1030    }
1031
1032    protected void validate(
1033            long groupId, long folderId, long newFolderId, String name,
1034            String title, String sourceFileName, InputStream is)
1035        throws PortalException, SystemException {
1036
1037        if (Validator.isNotNull(sourceFileName)) {
1038            dlLocalService.validate(name, sourceFileName, is);
1039        }
1040
1041        if (newFolderId > 0 && (folderId != newFolderId)) {
1042            folderId = newFolderId;
1043        }
1044
1045        String extension = FileUtil.getExtension(name);
1046
1047        try {
1048            String titleWithException = title;
1049
1050            if (Validator.isNotNull(extension)) {
1051                titleWithException += StringPool.PERIOD + extension;
1052            }
1053
1054            dlFolderLocalService.getFolder(
1055                groupId, newFolderId, titleWithException);
1056
1057            throw new DuplicateFolderNameException();
1058        }
1059        catch (NoSuchFolderException nsfe) {
1060        }
1061
1062        List<DLFileEntry> fileEntries = dlFileEntryPersistence.findByF_T(
1063            folderId, title);
1064
1065        for (DLFileEntry fileEntry : fileEntries) {
1066            if (!name.equals(fileEntry.getName())) {
1067                String curExtension = FileUtil.getExtension(
1068                    fileEntry.getName());
1069
1070                if (PropsValues.WEBDAV_LITMUS && Validator.isNull(extension)) {
1071                    if (Validator.isNull(curExtension)) {
1072                        throw new DuplicateFileException(
1073                            fileEntry.getTitleWithExtension());
1074                    }
1075                }
1076                else if (extension.equals(curExtension)) {
1077                    throw new DuplicateFileException(
1078                        fileEntry.getTitleWithExtension());
1079                }
1080            }
1081        }
1082    }
1083
1084    protected void validate(
1085            long groupId, long folderId, String name, String title,
1086            InputStream is)
1087        throws PortalException, SystemException {
1088
1089        dlLocalService.validate(name, is);
1090
1091        String extension = FileUtil.getExtension(name);
1092
1093        try {
1094            String titleWithException = title;
1095
1096            if (Validator.isNotNull(extension)) {
1097                titleWithException += StringPool.PERIOD + extension;
1098            }
1099
1100            dlFolderLocalService.getFolder(
1101                groupId, folderId, titleWithException);
1102
1103            throw new DuplicateFolderNameException();
1104        }
1105        catch (NoSuchFolderException nsfe) {
1106        }
1107
1108        List<DLFileEntry> fileEntries = dlFileEntryPersistence.findByF_T(
1109            folderId, title);
1110
1111        for (DLFileEntry fileEntry : fileEntries) {
1112            String curExtension = FileUtil.getExtension(fileEntry.getName());
1113
1114            if (PropsValues.WEBDAV_LITMUS && Validator.isNull(extension)) {
1115                if (Validator.isNull(curExtension)) {
1116                    throw new DuplicateFileException(
1117                        fileEntry.getTitleWithExtension());
1118                }
1119            }
1120            else if (extension.equals(curExtension)) {
1121                throw new DuplicateFileException(
1122                    fileEntry.getTitleWithExtension());
1123            }
1124        }
1125    }
1126
1127    private static Log _log =
1128        LogFactory.getLog(DLFileEntryLocalServiceImpl.class);
1129
1130}