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.bookmarks.service.impl;
016    
017    import com.liferay.portal.kernel.exception.PortalException;
018    import com.liferay.portal.kernel.exception.SystemException;
019    import com.liferay.portal.kernel.json.JSONFactoryUtil;
020    import com.liferay.portal.kernel.json.JSONObject;
021    import com.liferay.portal.kernel.log.Log;
022    import com.liferay.portal.kernel.log.LogFactoryUtil;
023    import com.liferay.portal.kernel.search.Indexable;
024    import com.liferay.portal.kernel.search.IndexableType;
025    import com.liferay.portal.kernel.util.ArrayUtil;
026    import com.liferay.portal.kernel.util.ContentTypes;
027    import com.liferay.portal.kernel.util.OrderByComparator;
028    import com.liferay.portal.kernel.util.StringPool;
029    import com.liferay.portal.kernel.util.Validator;
030    import com.liferay.portal.model.ResourceConstants;
031    import com.liferay.portal.model.User;
032    import com.liferay.portal.service.ServiceContext;
033    import com.liferay.portal.service.ServiceContextUtil;
034    import com.liferay.portal.util.Portal;
035    import com.liferay.portal.util.PortletKeys;
036    import com.liferay.portal.util.SubscriptionSender;
037    import com.liferay.portlet.asset.model.AssetEntry;
038    import com.liferay.portlet.asset.model.AssetLinkConstants;
039    import com.liferay.portlet.bookmarks.EntryURLException;
040    import com.liferay.portlet.bookmarks.model.BookmarksEntry;
041    import com.liferay.portlet.bookmarks.model.BookmarksFolder;
042    import com.liferay.portlet.bookmarks.model.BookmarksFolderConstants;
043    import com.liferay.portlet.bookmarks.service.base.BookmarksEntryLocalServiceBaseImpl;
044    import com.liferay.portlet.bookmarks.social.BookmarksActivityKeys;
045    import com.liferay.portlet.bookmarks.util.BookmarksUtil;
046    import com.liferay.portlet.bookmarks.util.comparator.EntryModifiedDateComparator;
047    
048    import java.util.Date;
049    import java.util.List;
050    import java.util.Locale;
051    import java.util.Map;
052    
053    import javax.portlet.PortletPreferences;
054    
055    /**
056     * @author Brian Wing Shun Chan
057     * @author Raymond Augé
058     */
059    public class BookmarksEntryLocalServiceImpl
060            extends BookmarksEntryLocalServiceBaseImpl {
061    
062            @Indexable(type = IndexableType.REINDEX)
063            public BookmarksEntry addEntry(
064                            long userId, long groupId, long folderId, String name, String url,
065                            String description, ServiceContext serviceContext)
066                    throws PortalException, SystemException {
067    
068                    // Entry
069    
070                    User user = userPersistence.findByPrimaryKey(userId);
071    
072                    if (Validator.isNull(name)) {
073                            name = url;
074                    }
075    
076                    Date now = new Date();
077    
078                    validate(url);
079    
080                    long entryId = counterLocalService.increment();
081    
082                    BookmarksEntry entry = bookmarksEntryPersistence.create(entryId);
083    
084                    entry.setUuid(serviceContext.getUuid());
085                    entry.setGroupId(groupId);
086                    entry.setCompanyId(user.getCompanyId());
087                    entry.setUserId(user.getUserId());
088                    entry.setUserName(user.getFullName());
089                    entry.setCreateDate(serviceContext.getCreateDate(now));
090                    entry.setModifiedDate(serviceContext.getModifiedDate(now));
091                    entry.setFolderId(folderId);
092                    entry.setName(name);
093                    entry.setUrl(url);
094                    entry.setDescription(description);
095                    entry.setExpandoBridgeAttributes(serviceContext);
096    
097                    bookmarksEntryPersistence.update(entry);
098    
099                    // Resources
100    
101                    resourceLocalService.addModelResources(entry, serviceContext);
102    
103                    // Asset
104    
105                    updateAsset(
106                            userId, entry, serviceContext.getAssetCategoryIds(),
107                            serviceContext.getAssetTagNames(),
108                            serviceContext.getAssetLinkEntryIds());
109    
110                    // Social
111    
112                    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();
113    
114                    extraDataJSONObject.put("title", entry.getName());
115    
116                    socialActivityLocalService.addActivity(
117                            userId, groupId, BookmarksEntry.class.getName(), entryId,
118                            BookmarksActivityKeys.ADD_ENTRY, extraDataJSONObject.toString(), 0);
119    
120                    // Subscriptions
121    
122                    notifySubscribers(entry, serviceContext);
123    
124                    return entry;
125            }
126    
127            public void deleteEntries(long groupId, long folderId)
128                    throws PortalException, SystemException {
129    
130                    List<BookmarksEntry> entries = bookmarksEntryPersistence.findByG_F(
131                            groupId, folderId);
132    
133                    for (BookmarksEntry entry : entries) {
134                            bookmarksEntryLocalService.deleteEntry(entry);
135                    }
136            }
137    
138            @Indexable(type = IndexableType.DELETE)
139            public BookmarksEntry deleteEntry(BookmarksEntry entry)
140                    throws PortalException, SystemException {
141    
142                    // Entry
143    
144                    bookmarksEntryPersistence.remove(entry);
145    
146                    // Resources
147    
148                    resourceLocalService.deleteResource(
149                            entry, ResourceConstants.SCOPE_INDIVIDUAL);
150    
151                    // Asset
152    
153                    assetEntryLocalService.deleteEntry(
154                            BookmarksEntry.class.getName(), entry.getEntryId());
155    
156                    // Expando
157    
158                    expandoValueLocalService.deleteValues(
159                            BookmarksEntry.class.getName(), entry.getEntryId());
160    
161                    // Subscriptions
162    
163                    subscriptionLocalService.deleteSubscriptions(
164                            entry.getCompanyId(), BookmarksEntry.class.getName(),
165                            entry.getEntryId());
166    
167                    return entry;
168            }
169    
170            @Indexable(type = IndexableType.DELETE)
171            public BookmarksEntry deleteEntry(long entryId)
172                    throws PortalException, SystemException {
173    
174                    BookmarksEntry entry = bookmarksEntryPersistence.findByPrimaryKey(
175                            entryId);
176    
177                    return deleteEntry(entry);
178            }
179    
180            public List<BookmarksEntry> getEntries(
181                            long groupId, long folderId, int start, int end)
182                    throws SystemException {
183    
184                    return bookmarksEntryPersistence.findByG_F(
185                            groupId, folderId, start, end);
186            }
187    
188            public List<BookmarksEntry> getEntries(
189                            long groupId, long folderId, int start, int end,
190                            OrderByComparator orderByComparator)
191                    throws SystemException {
192    
193                    return bookmarksEntryPersistence.findByG_F(
194                            groupId, folderId, start, end, orderByComparator);
195            }
196    
197            public int getEntriesCount(long groupId, long folderId)
198                    throws SystemException {
199    
200                    return bookmarksEntryPersistence.countByG_F(groupId, folderId);
201            }
202    
203            public BookmarksEntry getEntry(long entryId)
204                    throws PortalException, SystemException {
205    
206                    return bookmarksEntryPersistence.findByPrimaryKey(entryId);
207            }
208    
209            public int getFoldersEntriesCount(long groupId, List<Long> folderIds)
210                    throws SystemException {
211    
212                    return bookmarksEntryPersistence.countByG_F(
213                            groupId,
214                            ArrayUtil.toArray(folderIds.toArray(new Long[folderIds.size()])));
215            }
216    
217            public List<BookmarksEntry> getGroupEntries(
218                            long groupId, int start, int end)
219                    throws SystemException {
220    
221                    return bookmarksEntryPersistence.findByGroupId(
222                            groupId, start, end, new EntryModifiedDateComparator());
223            }
224    
225            public List<BookmarksEntry> getGroupEntries(
226                            long groupId, long userId, int start, int end)
227                    throws SystemException {
228    
229                    OrderByComparator orderByComparator = new EntryModifiedDateComparator();
230    
231                    if (userId <= 0) {
232                            return bookmarksEntryPersistence.findByGroupId(
233                                    groupId, start, end, orderByComparator);
234                    }
235                    else {
236                            return bookmarksEntryPersistence.findByG_U(
237                                    groupId, userId, start, end, orderByComparator);
238                    }
239            }
240    
241            public int getGroupEntriesCount(long groupId) throws SystemException {
242                    return bookmarksEntryPersistence.countByGroupId(groupId);
243            }
244    
245            public int getGroupEntriesCount(long groupId, long userId)
246                    throws SystemException {
247    
248                    if (userId <= 0) {
249                            return bookmarksEntryPersistence.countByGroupId(groupId);
250                    }
251                    else {
252                            return bookmarksEntryPersistence.countByG_U(groupId, userId);
253                    }
254            }
255    
256            public List<BookmarksEntry> getNoAssetEntries() throws SystemException {
257                    return bookmarksEntryFinder.findByNoAssets();
258            }
259    
260            public BookmarksEntry openEntry(long userId, long entryId)
261                    throws PortalException, SystemException {
262    
263                    BookmarksEntry entry = bookmarksEntryPersistence.findByPrimaryKey(
264                            entryId);
265    
266                    entry.setVisits(entry.getVisits() + 1);
267    
268                    bookmarksEntryPersistence.update(entry);
269    
270                    assetEntryLocalService.incrementViewCounter(
271                            userId, BookmarksEntry.class.getName(), entryId, 1);
272    
273                    return entry;
274            }
275    
276            public void subscribeEntry(long userId, long entryId)
277                    throws PortalException, SystemException {
278    
279                    BookmarksEntry entry = bookmarksEntryPersistence.findByPrimaryKey(
280                            entryId);
281    
282                    subscriptionLocalService.addSubscription(
283                            userId, entry.getGroupId(), BookmarksEntry.class.getName(),
284                            entryId);
285            }
286    
287            public void unsubscribeEntry(long userId, long entryId)
288                    throws PortalException, SystemException {
289    
290                    subscriptionLocalService.deleteSubscription(
291                            userId, BookmarksEntry.class.getName(), entryId);
292            }
293    
294            public void updateAsset(
295                            long userId, BookmarksEntry entry, long[] assetCategoryIds,
296                            String[] assetTagNames, long[] assetLinkEntryIds)
297                    throws PortalException, SystemException {
298    
299                    AssetEntry assetEntry = assetEntryLocalService.updateEntry(
300                            userId, entry.getGroupId(), entry.getCreateDate(),
301                            entry.getModifiedDate(), BookmarksEntry.class.getName(),
302                            entry.getEntryId(), entry.getUuid(), 0, assetCategoryIds,
303                            assetTagNames, true, null, null, null, ContentTypes.TEXT_PLAIN,
304                            entry.getName(), entry.getDescription(), null, entry.getUrl(), null,
305                            0, 0, null, false);
306    
307                    assetLinkLocalService.updateLinks(
308                            userId, assetEntry.getEntryId(), assetLinkEntryIds,
309                            AssetLinkConstants.TYPE_RELATED);
310            }
311    
312            @Indexable(type = IndexableType.REINDEX)
313            public BookmarksEntry updateEntry(
314                            long userId, long entryId, long groupId, long folderId, String name,
315                            String url, String description, ServiceContext serviceContext)
316                    throws PortalException, SystemException {
317    
318                    // Entry
319    
320                    BookmarksEntry entry = bookmarksEntryPersistence.findByPrimaryKey(
321                            entryId);
322    
323                    if (Validator.isNull(name)) {
324                            name = url;
325                    }
326    
327                    validate(url);
328    
329                    entry.setModifiedDate(serviceContext.getModifiedDate(null));
330                    entry.setFolderId(folderId);
331                    entry.setName(name);
332                    entry.setUrl(url);
333                    entry.setDescription(description);
334                    entry.setExpandoBridgeAttributes(serviceContext);
335    
336                    bookmarksEntryPersistence.update(entry);
337    
338                    // Asset
339    
340                    updateAsset(
341                            userId, entry, serviceContext.getAssetCategoryIds(),
342                            serviceContext.getAssetTagNames(),
343                            serviceContext.getAssetLinkEntryIds());
344    
345                    // Social
346    
347                    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();
348    
349                    extraDataJSONObject.put("title", entry.getName());
350    
351                    socialActivityLocalService.addActivity(
352                            userId, entry.getGroupId(), BookmarksEntry.class.getName(), entryId,
353                            BookmarksActivityKeys.UPDATE_ENTRY, extraDataJSONObject.toString(),
354                            0);
355    
356                    // Subscriptions
357    
358                    notifySubscribers(entry, serviceContext);
359    
360                    return entry;
361            }
362    
363            protected long getFolder(BookmarksEntry entry, long folderId)
364                    throws SystemException {
365    
366                    if ((entry.getFolderId() != folderId) &&
367                            (folderId != BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID)) {
368    
369                            BookmarksFolder newFolder =
370                                    bookmarksFolderPersistence.fetchByPrimaryKey(folderId);
371    
372                            if ((newFolder == null) ||
373                                    (entry.getGroupId() != newFolder.getGroupId())) {
374    
375                                    folderId = entry.getFolderId();
376                            }
377                    }
378    
379                    return folderId;
380            }
381    
382            protected void notifySubscribers(
383                            BookmarksEntry entry, ServiceContext serviceContext)
384                    throws PortalException, SystemException {
385    
386                    String layoutFullURL = serviceContext.getLayoutFullURL();
387    
388                    if (Validator.isNull(layoutFullURL)) {
389                            return;
390                    }
391    
392                    PortletPreferences preferences =
393                            ServiceContextUtil.getPortletPreferences(serviceContext);
394    
395                    if (preferences == null) {
396                            long ownerId = entry.getGroupId();
397                            int ownerType = PortletKeys.PREFS_OWNER_TYPE_GROUP;
398                            long plid = PortletKeys.PREFS_PLID_SHARED;
399                            String portletId = PortletKeys.BOOKMARKS;
400                            String defaultPreferences = null;
401    
402                            preferences = portletPreferencesLocalService.getPreferences(
403                                    entry.getCompanyId(), ownerId, ownerType, plid, portletId,
404                                    defaultPreferences);
405                    }
406    
407                    if ((serviceContext.isCommandAdd() &&
408                             !BookmarksUtil.getEmailEntryAddedEnabled(preferences)) ||
409                            (serviceContext.isCommandUpdate() &&
410                             !BookmarksUtil.getEmailEntryUpdatedEnabled(preferences))) {
411    
412                            return;
413                    }
414    
415                    String statusByUserName = StringPool.BLANK;
416    
417                    try {
418                            User user = userLocalService.getUserById(
419                                    serviceContext.getGuestOrUserId());
420    
421                            statusByUserName = user.getFullName();
422                    }
423                    catch (Exception e) {
424                            _log.error(e, e);
425                    }
426    
427                    String entryURL =
428                            layoutFullURL + Portal.FRIENDLY_URL_SEPARATOR + "bookmarks" +
429                                    StringPool.SLASH + entry.getEntryId();
430    
431                    String fromAddress = BookmarksUtil.getEmailFromAddress(
432                            preferences, entry.getCompanyId());
433                    String fromName = BookmarksUtil.getEmailFromName(
434                            preferences, entry.getCompanyId());
435    
436                    Map<Locale, String> localizedSubjectMap = null;
437                    Map<Locale, String> localizedBodyMap = null;
438    
439                    if (serviceContext.isCommandUpdate()) {
440                            localizedSubjectMap = BookmarksUtil.getEmailEntryUpdatedSubjectMap(
441                                    preferences);
442                            localizedBodyMap = BookmarksUtil.getEmailEntryUpdatedBodyMap(
443                                    preferences);
444                    }
445                    else {
446                            localizedSubjectMap = BookmarksUtil.getEmailEntryAddedSubjectMap(
447                                    preferences);
448                            localizedBodyMap = BookmarksUtil.getEmailEntryAddedBodyMap(
449                                    preferences);
450                    }
451    
452                    SubscriptionSender subscriptionSender = new SubscriptionSender();
453    
454                    subscriptionSender.setCompanyId(entry.getCompanyId());
455                    subscriptionSender.setContextAttributes(
456                            "[$BOOKMARKS_ENTRY_STATUS_BY_USER_NAME$]", statusByUserName,
457                            "[$BOOKMARKS_ENTRY_URL$]", entryURL);
458                    subscriptionSender.setContextUserPrefix("BOOKMARKS_ENTRY");
459                    subscriptionSender.setFrom(fromAddress, fromName);
460                    subscriptionSender.setHtmlFormat(true);
461                    subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
462                    subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
463                    subscriptionSender.setMailId("bookmarks_entry", entry.getEntryId());
464                    subscriptionSender.setPortletId(PortletKeys.BOOKMARKS);
465                    subscriptionSender.setReplyToAddress(fromAddress);
466                    subscriptionSender.setScopeGroupId(entry.getGroupId());
467                    subscriptionSender.setServiceContext(serviceContext);
468                    subscriptionSender.setUserId(entry.getUserId());
469    
470                    subscriptionSender.addPersistedSubscribers(
471                            BookmarksEntry.class.getName(), entry.getEntryId());
472    
473                    BookmarksFolder folder = entry.getFolder();
474    
475                    if (folder.getFolderId() !=
476                                    BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
477    
478                            subscriptionSender.addPersistedSubscribers(
479                                    BookmarksFolder.class.getName(), folder.getFolderId());
480    
481                            for (BookmarksFolder ancestor : folder.getAncestors()) {
482                                    subscriptionSender.addPersistedSubscribers(
483                                            BookmarksFolder.class.getName(), ancestor.getFolderId());
484                            }
485                    }
486    
487                    subscriptionSender.addPersistedSubscribers(
488                            BookmarksFolder.class.getName(), folder.getGroupId());
489    
490                    subscriptionSender.flushNotificationsAsync();
491            }
492    
493            protected void validate(String url) throws PortalException {
494                    if (!Validator.isUrl(url)) {
495                            throw new EntryURLException();
496                    }
497            }
498    
499            private static Log _log = LogFactoryUtil.getLog(
500                    BookmarksEntryLocalServiceImpl.class);
501    
502    }