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