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.asset.service.impl;
016    
017    import com.liferay.portal.kernel.cache.ThreadLocalCachable;
018    import com.liferay.portal.kernel.dao.orm.QueryUtil;
019    import com.liferay.portal.kernel.exception.PortalException;
020    import com.liferay.portal.kernel.exception.SystemException;
021    import com.liferay.portal.kernel.util.ArrayUtil;
022    import com.liferay.portal.kernel.util.CharPool;
023    import com.liferay.portal.kernel.util.GetterUtil;
024    import com.liferay.portal.kernel.util.ListUtil;
025    import com.liferay.portal.kernel.util.StringPool;
026    import com.liferay.portal.kernel.util.StringUtil;
027    import com.liferay.portal.kernel.util.Validator;
028    import com.liferay.portal.model.ResourceConstants;
029    import com.liferay.portal.model.User;
030    import com.liferay.portal.service.ServiceContext;
031    import com.liferay.portal.util.PortalUtil;
032    import com.liferay.portal.util.PropsValues;
033    import com.liferay.portlet.asset.AssetTagException;
034    import com.liferay.portlet.asset.DuplicateTagException;
035    import com.liferay.portlet.asset.NoSuchTagException;
036    import com.liferay.portlet.asset.model.AssetEntry;
037    import com.liferay.portlet.asset.model.AssetTag;
038    import com.liferay.portlet.asset.model.AssetTagProperty;
039    import com.liferay.portlet.asset.service.base.AssetTagLocalServiceBaseImpl;
040    import com.liferay.portlet.asset.util.AssetUtil;
041    import com.liferay.portlet.social.util.SocialCounterPeriodUtil;
042    
043    import java.util.ArrayList;
044    import java.util.Date;
045    import java.util.List;
046    
047    /**
048     * @author Brian Wing Shun Chan
049     * @author Alvaro del Castillo
050     * @author Jorge Ferrer
051     * @author Bruno Farache
052     */
053    public class AssetTagLocalServiceImpl extends AssetTagLocalServiceBaseImpl {
054    
055            public AssetTag addTag(
056                            long userId, String name, String[] tagProperties,
057                            ServiceContext serviceContext)
058                    throws PortalException, SystemException {
059    
060                    // Tag
061    
062                    User user = userPersistence.findByPrimaryKey(userId);
063                    long groupId = serviceContext.getScopeGroupId();
064    
065                    if (tagProperties == null) {
066                            tagProperties = new String[0];
067                    }
068    
069                    Date now = new Date();
070    
071                    long tagId = counterLocalService.increment();
072    
073                    AssetTag tag = assetTagPersistence.create(tagId);
074    
075                    tag.setGroupId(groupId);
076                    tag.setCompanyId(user.getCompanyId());
077                    tag.setUserId(user.getUserId());
078                    tag.setUserName(user.getFullName());
079                    tag.setCreateDate(now);
080                    tag.setModifiedDate(now);
081    
082                    name = name.trim();
083                    name = name.toLowerCase();
084    
085                    if (hasTag(groupId, name)) {
086                            throw new DuplicateTagException(
087                                    "A tag with the name " + name + " already exists");
088                    }
089    
090                    validate(name);
091    
092                    tag.setName(name);
093    
094                    assetTagPersistence.update(tag, false);
095    
096                    // Resources
097    
098                    if (serviceContext.isAddGroupPermissions() ||
099                            serviceContext.isAddGuestPermissions()) {
100    
101                            addTagResources(
102                                    tag, serviceContext.isAddGroupPermissions(),
103                                    serviceContext.isAddGuestPermissions());
104                    }
105                    else {
106                            addTagResources(
107                                    tag, serviceContext.getGroupPermissions(),
108                                    serviceContext.getGuestPermissions());
109                    }
110    
111                    // Properties
112    
113                    for (int i = 0; i < tagProperties.length; i++) {
114                            String[] tagProperty = StringUtil.split(
115                                    tagProperties[i], CharPool.COLON);
116    
117                            String key = StringPool.BLANK;
118    
119                            if (tagProperty.length > 0) {
120                                    key = GetterUtil.getString(tagProperty[0]);
121                            }
122    
123                            String value = StringPool.BLANK;
124    
125                            if (tagProperty.length > 1) {
126                                    value = GetterUtil.getString(tagProperty[1]);
127                            }
128    
129                            if (Validator.isNotNull(key)) {
130                                    assetTagPropertyLocalService.addTagProperty(
131                                            userId, tagId, key, value);
132                            }
133                    }
134    
135                    return tag;
136            }
137    
138            public void addTagResources(
139                            AssetTag tag, boolean addGroupPermissions,
140                            boolean addGuestPermissions)
141                    throws PortalException, SystemException {
142    
143                    resourceLocalService.addResources(
144                            tag.getCompanyId(), tag.getGroupId(), tag.getUserId(),
145                            AssetTag.class.getName(), tag.getTagId(), false,
146                            addGroupPermissions, addGuestPermissions);
147            }
148    
149            public void addTagResources(
150                            AssetTag tag, String[] groupPermissions, String[] guestPermissions)
151                    throws PortalException, SystemException {
152    
153                    resourceLocalService.addModelResources(
154                            tag.getCompanyId(), tag.getGroupId(), tag.getUserId(),
155                            AssetTag.class.getName(), tag.getTagId(), groupPermissions,
156                            guestPermissions);
157            }
158    
159            public void checkTags(long userId, long groupId, String[] names)
160                    throws PortalException, SystemException {
161    
162                    for (String name : names) {
163                            try {
164                                    getTag(groupId, name);
165                            }
166                            catch (NoSuchTagException nste) {
167                                    ServiceContext serviceContext = new ServiceContext();
168    
169                                    serviceContext.setAddGroupPermissions(true);
170                                    serviceContext.setAddGuestPermissions(true);
171                                    serviceContext.setScopeGroupId(groupId);
172    
173                                    addTag(
174                                            userId, name, PropsValues.ASSET_TAG_PROPERTIES_DEFAULT,
175                                            serviceContext);
176                            }
177                    }
178            }
179    
180            public AssetTag decrementAssetCount(long tagId, long classNameId)
181                    throws PortalException, SystemException {
182    
183                    AssetTag tag = assetTagPersistence.findByPrimaryKey(tagId);
184    
185                    tag.setAssetCount(Math.max(0, tag.getAssetCount() - 1));
186    
187                    assetTagPersistence.update(tag, false);
188    
189                    assetTagStatsLocalService.updateTagStats(tagId, classNameId);
190    
191                    return tag;
192            }
193    
194            public void deleteTag(AssetTag tag)
195                    throws PortalException, SystemException {
196    
197                    // Entries
198    
199                    List<AssetEntry> entries = assetTagPersistence.getAssetEntries(
200                            tag.getTagId());
201    
202                    // Tag
203    
204                    assetTagPersistence.remove(tag);
205    
206                    // Resources
207    
208                    resourceLocalService.deleteResource(
209                            tag.getCompanyId(), AssetTag.class.getName(),
210                            ResourceConstants.SCOPE_INDIVIDUAL, tag.getTagId());
211    
212                    // Properties
213    
214                    assetTagPropertyLocalService.deleteTagProperties(tag.getTagId());
215    
216                    // Indexer
217    
218                    assetEntryLocalService.reindex(entries);
219            }
220    
221            public void deleteTag(long tagId) throws PortalException, SystemException {
222                    AssetTag tag = assetTagPersistence.findByPrimaryKey(tagId);
223    
224                    deleteTag(tag);
225            }
226    
227            public List<AssetTag> getEntryTags(long entryId) throws SystemException {
228                    return assetTagFinder.findByEntryId(entryId);
229            }
230    
231            public List<AssetTag> getGroupsTags(long[] groupIds)
232                    throws SystemException {
233    
234                    List<AssetTag> groupsTags = new ArrayList<AssetTag>();
235    
236                    for (long groupId : groupIds) {
237                            List<AssetTag> groupTags = getGroupTags(groupId);
238    
239                            groupsTags.addAll(groupTags);
240                    }
241    
242                    return groupsTags;
243            }
244    
245            public List<AssetTag> getGroupTags(long groupId) throws SystemException {
246                    return assetTagPersistence.findByGroupId(groupId);
247            }
248    
249            public List<AssetTag> getGroupTags(long groupId, int start, int end)
250                    throws SystemException {
251    
252                    return assetTagPersistence.findByGroupId(groupId, start, end);
253            }
254    
255            public int getGroupTagsCount(long groupId) throws SystemException {
256                    return assetTagPersistence.countByGroupId(groupId);
257            }
258    
259            public List<AssetTag> getSocialActivityCounterOffsetTags(
260                            long groupId, String socialActivityCounterName, int startOffset,
261                            int endOffset)
262                    throws SystemException {
263    
264                    int startPeriod = SocialCounterPeriodUtil.getStartPeriod(startOffset);
265                    int endPeriod = SocialCounterPeriodUtil.getEndPeriod(endOffset);
266    
267                    return getSocialActivityCounterPeriodTags(
268                            groupId, socialActivityCounterName, startPeriod, endPeriod);
269            }
270    
271            public List<AssetTag> getSocialActivityCounterPeriodTags(
272                            long groupId, String socialActivityCounterName, int startPeriod,
273                            int endPeriod)
274                    throws SystemException {
275    
276                    int offset = SocialCounterPeriodUtil.getOffset(endPeriod);
277    
278                    int periodLength = SocialCounterPeriodUtil.getPeriodLength(offset);
279    
280                    return assetTagFinder.findByG_N_S_E(
281                            groupId, socialActivityCounterName, startPeriod, endPeriod,
282                            periodLength);
283            }
284    
285            public AssetTag getTag(long tagId) throws PortalException, SystemException {
286                    return assetTagPersistence.findByPrimaryKey(tagId);
287            }
288    
289            public AssetTag getTag(long groupId, String name)
290                    throws PortalException, SystemException {
291    
292                    return assetTagFinder.findByG_N(groupId, name);
293            }
294    
295            public long[] getTagIds(long groupId, String[] names)
296                    throws PortalException, SystemException {
297    
298                    List<Long> tagIds = new ArrayList<Long>(names.length);
299    
300                    for (String name : names) {
301                            try {
302                                    AssetTag tag = getTag(groupId, name);
303    
304                                    tagIds.add(tag.getTagId());
305                            }
306                            catch (NoSuchTagException nste) {
307                            }
308                    }
309    
310                    return ArrayUtil.toArray(tagIds.toArray(new Long[tagIds.size()]));
311            }
312    
313            public long[] getTagIds(long[] groupIds, String[] names)
314                    throws PortalException, SystemException {
315    
316                    long[] tagsIds = new long[0];
317    
318                    for (long groupId : groupIds) {
319                            tagsIds = ArrayUtil.append(tagsIds, getTagIds(groupId, names));
320                    }
321    
322                    return tagsIds;
323            }
324    
325            public String[] getTagNames() throws SystemException {
326                    return getTagNames(getTags());
327            }
328    
329            public String[] getTagNames(long classNameId, long classPK)
330                    throws SystemException {
331    
332                    return getTagNames(getTags(classNameId, classPK));
333            }
334    
335            public String[] getTagNames(String className, long classPK)
336                    throws SystemException {
337    
338                    return getTagNames(getTags(className, classPK));
339            }
340    
341            public List<AssetTag> getTags() throws SystemException {
342                    return assetTagPersistence.findAll();
343            }
344    
345            public List<AssetTag> getTags(long classNameId, long classPK)
346                    throws SystemException {
347    
348                    return assetTagFinder.findByC_C(classNameId, classPK);
349            }
350    
351            public List<AssetTag> getTags(long groupId, long classNameId, String name)
352                    throws SystemException {
353    
354                    return assetTagFinder.findByG_C_N(
355                            groupId, classNameId, name, QueryUtil.ALL_POS, QueryUtil.ALL_POS,
356                            null);
357            }
358    
359            public List<AssetTag> getTags(
360                            long groupId, long classNameId, String name, int start, int end)
361                    throws SystemException {
362    
363                    return assetTagFinder.findByG_C_N(
364                            groupId, classNameId, name, start, end, null);
365            }
366    
367            @ThreadLocalCachable
368            public List<AssetTag> getTags(String className, long classPK)
369                    throws SystemException {
370    
371                    long classNameId = PortalUtil.getClassNameId(className);
372    
373                    return getTags(classNameId, classPK);
374            }
375    
376            public int getTagsSize(long groupId, long classNameId, String name)
377                    throws SystemException {
378    
379                    return assetTagFinder.countByG_C_N(groupId, classNameId, name);
380            }
381    
382            public boolean hasTag(long groupId, String name)
383                    throws PortalException, SystemException {
384    
385                    try {
386                            getTag(groupId, name);
387    
388                            return true;
389                    }
390                    catch (NoSuchTagException nste) {
391                            return false;
392                    }
393            }
394    
395            public AssetTag incrementAssetCount(long tagId, long classNameId)
396                    throws PortalException, SystemException {
397    
398                    AssetTag tag = assetTagPersistence.findByPrimaryKey(tagId);
399    
400                    tag.setAssetCount(tag.getAssetCount() + 1);
401    
402                    assetTagPersistence.update(tag, false);
403    
404                    assetTagStatsLocalService.updateTagStats(tagId, classNameId);
405    
406                    return tag;
407            }
408    
409            public void mergeTags(
410                            long fromTagId, long toTagId, boolean overrideProperties)
411                    throws PortalException, SystemException {
412    
413                    List<AssetEntry> entries = assetTagPersistence.getAssetEntries(
414                            fromTagId);
415    
416                    assetTagPersistence.addAssetEntries(toTagId, entries);
417    
418                    List<AssetTagProperty> tagProperties =
419                            assetTagPropertyPersistence.findByTagId(fromTagId);
420    
421                    for (AssetTagProperty fromTagProperty : tagProperties) {
422                            AssetTagProperty toTagProperty =
423                                    assetTagPropertyPersistence.fetchByT_K(
424                                            toTagId, fromTagProperty.getKey());
425    
426                            if (overrideProperties && (toTagProperty != null)) {
427                                    toTagProperty.setValue(fromTagProperty.getValue());
428    
429                                    assetTagPropertyPersistence.update(toTagProperty, false);
430                            }
431                            else if (toTagProperty == null) {
432                                    fromTagProperty.setTagId(toTagId);
433    
434                                    assetTagPropertyPersistence.update(fromTagProperty, false);
435                            }
436                    }
437    
438                    deleteTag(fromTagId);
439            }
440    
441            public List<AssetTag> search(
442                            long groupId, String name, String[] tagProperties, int start,
443                            int end)
444                    throws SystemException {
445    
446                    return assetTagFinder.findByG_N_P(
447                            groupId, name, tagProperties, start, end, null);
448            }
449    
450            public AssetTag updateTag(
451                            long userId, long tagId, String name, String[] tagProperties,
452                            ServiceContext serviceContext)
453                    throws PortalException, SystemException {
454    
455                    // Tag
456    
457                    AssetTag tag = assetTagPersistence.findByPrimaryKey(tagId);
458    
459                    String oldName = tag.getName();
460    
461                    tag.setModifiedDate(new Date());
462    
463                    name = name.trim();
464                    name = name.toLowerCase();
465    
466                    if (tagProperties == null) {
467                            tagProperties = new String[0];
468                    }
469    
470                    if (!name.equals(tag.getName()) && hasTag(tag.getGroupId(), name)) {
471                            throw new DuplicateTagException(
472                                    "A tag with the name " + name + " already exists");
473                    }
474    
475                    if (!tag.getName().equals(name)) {
476                            try {
477                                    AssetTag existingAssetTag = getTag(tag.getGroupId(), name);
478    
479                                    if (existingAssetTag.getTagId() != tagId) {
480                                            throw new DuplicateTagException(
481                                                    "A tag with the name " + name + " already exists");
482                                    }
483                            }
484                            catch (NoSuchTagException nste) {
485                            }
486                    }
487    
488                    validate(name);
489    
490                    tag.setName(name);
491    
492                    assetTagPersistence.update(tag, false);
493    
494                    // Properties
495    
496                    List<AssetTagProperty> oldTagProperties =
497                            assetTagPropertyPersistence.findByTagId(tagId);
498    
499                    for (AssetTagProperty tagProperty : oldTagProperties) {
500                            assetTagPropertyLocalService.deleteTagProperty(tagProperty);
501                    }
502    
503                    for (int i = 0; i < tagProperties.length; i++) {
504                            String[] tagProperty = StringUtil.split(
505                                    tagProperties[i], CharPool.COLON);
506    
507                            String key = StringPool.BLANK;
508    
509                            if (tagProperty.length > 0) {
510                                    key = GetterUtil.getString(tagProperty[0]);
511                            }
512    
513                            String value = StringPool.BLANK;
514    
515                            if (tagProperty.length > 1) {
516                                    value = GetterUtil.getString(tagProperty[1]);
517                            }
518    
519                            if (Validator.isNotNull(key)) {
520                                    assetTagPropertyLocalService.addTagProperty(
521                                            userId, tagId, key, value);
522                            }
523                    }
524    
525                    // Indexer
526    
527                    if (!oldName.equals(name)) {
528                            List<AssetEntry> entries = assetTagPersistence.getAssetEntries(
529                                    tag.getTagId());
530    
531                            assetEntryLocalService.reindex(entries);
532                    }
533    
534                    return tag;
535            }
536    
537            protected String[] getTagNames(List<AssetTag>tags) {
538                    return StringUtil.split(
539                            ListUtil.toString(tags, AssetTag.NAME_ACCESSOR));
540            }
541    
542            protected void validate(String name) throws PortalException {
543                    if (!AssetUtil.isValidWord(name)) {
544                            throw new AssetTagException(
545                                    StringUtil.merge(
546                                            AssetUtil.INVALID_CHARACTERS, StringPool.SPACE),
547                                    AssetTagException.INVALID_CHARACTER);
548                    }
549            }
550    
551    }