001    /**
002     * Copyright (c) 2000-present 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.util.ArrayUtil;
021    import com.liferay.portal.kernel.util.CharPool;
022    import com.liferay.portal.kernel.util.GetterUtil;
023    import com.liferay.portal.kernel.util.ListUtil;
024    import com.liferay.portal.kernel.util.StringPool;
025    import com.liferay.portal.kernel.util.StringUtil;
026    import com.liferay.portal.kernel.util.Validator;
027    import com.liferay.portal.model.Group;
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.PropsValues;
032    import com.liferay.portlet.asset.AssetTagException;
033    import com.liferay.portlet.asset.DuplicateTagException;
034    import com.liferay.portlet.asset.NoSuchTagException;
035    import com.liferay.portlet.asset.model.AssetEntry;
036    import com.liferay.portlet.asset.model.AssetTag;
037    import com.liferay.portlet.asset.model.AssetTagConstants;
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.Collections;
045    import java.util.Date;
046    import java.util.List;
047    
048    /**
049     * Provides the local service for accessing, adding, checking, deleting,
050     * merging, and updating asset tags.
051     *
052     * @author Brian Wing Shun Chan
053     * @author Alvaro del Castillo
054     * @author Jorge Ferrer
055     * @author Bruno Farache
056     */
057    public class AssetTagLocalServiceImpl extends AssetTagLocalServiceBaseImpl {
058    
059            @Override
060            public AssetTag addTag(
061                            long userId, String name, String[] tagProperties,
062                            ServiceContext serviceContext)
063                    throws PortalException {
064    
065                    // Tag
066    
067                    User user = userPersistence.findByPrimaryKey(userId);
068                    long groupId = serviceContext.getScopeGroupId();
069    
070                    if (tagProperties == null) {
071                            tagProperties = new String[0];
072                    }
073    
074                    Date now = new Date();
075    
076                    long tagId = counterLocalService.increment();
077    
078                    AssetTag tag = assetTagPersistence.create(tagId);
079    
080                    tag.setGroupId(groupId);
081                    tag.setCompanyId(user.getCompanyId());
082                    tag.setUserId(user.getUserId());
083                    tag.setUserName(user.getFullName());
084                    tag.setCreateDate(now);
085                    tag.setModifiedDate(now);
086    
087                    name = name.trim();
088                    name = StringUtil.toLowerCase(name);
089    
090                    if (hasTag(groupId, name)) {
091                            throw new DuplicateTagException(
092                                    "A tag with the name " + name + " already exists");
093                    }
094    
095                    validate(name);
096    
097                    tag.setName(name);
098    
099                    assetTagPersistence.update(tag);
100    
101                    // Resources
102    
103                    if (serviceContext.isAddGroupPermissions() ||
104                            serviceContext.isAddGuestPermissions()) {
105    
106                            addTagResources(
107                                    tag, serviceContext.isAddGroupPermissions(),
108                                    serviceContext.isAddGuestPermissions());
109                    }
110                    else {
111                            addTagResources(
112                                    tag, serviceContext.getGroupPermissions(),
113                                    serviceContext.getGuestPermissions());
114                    }
115    
116                    // Properties
117    
118                    for (int i = 0; i < tagProperties.length; i++) {
119                            String[] tagProperty = StringUtil.split(
120                                    tagProperties[i],
121                                    AssetTagConstants.PROPERTY_KEY_VALUE_SEPARATOR);
122    
123                            if (tagProperty.length <= 1) {
124                                    tagProperty = StringUtil.split(
125                                            tagProperties[i], CharPool.COLON);
126                            }
127    
128                            String key = StringPool.BLANK;
129    
130                            if (tagProperty.length > 0) {
131                                    key = GetterUtil.getString(tagProperty[0]);
132                            }
133    
134                            String value = StringPool.BLANK;
135    
136                            if (tagProperty.length > 1) {
137                                    value = GetterUtil.getString(tagProperty[1]);
138                            }
139    
140                            if (Validator.isNotNull(key)) {
141                                    assetTagPropertyLocalService.addTagProperty(
142                                            userId, tagId, key, value);
143                            }
144                    }
145    
146                    return tag;
147            }
148    
149            @Override
150            public void addTagResources(
151                            AssetTag tag, boolean addGroupPermissions,
152                            boolean addGuestPermissions)
153                    throws PortalException {
154    
155                    resourceLocalService.addResources(
156                            tag.getCompanyId(), tag.getGroupId(), tag.getUserId(),
157                            AssetTag.class.getName(), tag.getTagId(), false,
158                            addGroupPermissions, addGuestPermissions);
159            }
160    
161            @Override
162            public void addTagResources(
163                            AssetTag tag, String[] groupPermissions, String[] guestPermissions)
164                    throws PortalException {
165    
166                    resourceLocalService.addModelResources(
167                            tag.getCompanyId(), tag.getGroupId(), tag.getUserId(),
168                            AssetTag.class.getName(), tag.getTagId(), groupPermissions,
169                            guestPermissions);
170            }
171    
172            /**
173             * Returns the tags matching the group and names, creating new tags with the
174             * names if the group doesn't already have them.
175             *
176             * <p>
177             * For each name, if a tag with that name doesn't already exist for the
178             * group, this method creates a new tag with that name for the group. If a
179             * tag with that name already exists in the company group, this method
180             * copies that company group's tag's properties to the group's new tag.
181             * </p>
182             *
183             * @param  userId the primary key of the user
184             * @param  group ID the primary key of the tag's group
185             * @param  names the tag names
186             * @return the tags matching the group and names and new tags matching the
187             *         names that don't already exist for the group
188             * @throws PortalException if a matching group could not be found, if the
189             *         tag's key or value were invalid, or if a portal exception
190             *         occurred
191             */
192            @Override
193            public List<AssetTag> checkTags(long userId, Group group, String[] names)
194                    throws PortalException {
195    
196                    List<AssetTag> tags = new ArrayList<AssetTag>();
197    
198                    for (String name : names) {
199                            AssetTag tag = null;
200    
201                            try {
202                                    tag = getTag(group.getGroupId(), name);
203                            }
204                            catch (NoSuchTagException nste1) {
205                                    ServiceContext serviceContext = new ServiceContext();
206    
207                                    serviceContext.setAddGroupPermissions(true);
208                                    serviceContext.setAddGuestPermissions(true);
209                                    serviceContext.setScopeGroupId(group.getGroupId());
210    
211                                    tag = addTag(
212                                            userId, name, PropsValues.ASSET_TAG_PROPERTIES_DEFAULT,
213                                            serviceContext);
214    
215                                    Group companyGroup = groupLocalService.getCompanyGroup(
216                                            group.getCompanyId());
217    
218                                    try {
219                                            AssetTag companyGroupTag = getTag(
220                                                    companyGroup.getGroupId(), name);
221    
222                                            List<AssetTagProperty> tagProperties =
223                                                    assetTagPropertyLocalService.getTagProperties(
224                                                            companyGroupTag.getTagId());
225    
226                                            for (AssetTagProperty tagProperty : tagProperties) {
227                                                    assetTagPropertyLocalService.addTagProperty(
228                                                            userId, tag.getTagId(), tagProperty.getKey(),
229                                                            tagProperty.getValue());
230                                            }
231                                    }
232                                    catch (NoSuchTagException nste2) {
233                                    }
234                            }
235    
236                            if (tag != null) {
237                                    tags.add(tag);
238                            }
239                    }
240    
241                    return tags;
242            }
243    
244            @Override
245            public void checkTags(long userId, long groupId, String[] names)
246                    throws PortalException {
247    
248                    Group group = groupPersistence.findByPrimaryKey(groupId);
249    
250                    checkTags(userId, group, names);
251            }
252    
253            @Override
254            public AssetTag decrementAssetCount(long tagId, long classNameId)
255                    throws PortalException {
256    
257                    AssetTag tag = assetTagPersistence.findByPrimaryKey(tagId);
258    
259                    tag.setAssetCount(Math.max(0, tag.getAssetCount() - 1));
260    
261                    assetTagPersistence.update(tag);
262    
263                    assetTagStatsLocalService.updateTagStats(tagId, classNameId);
264    
265                    return tag;
266            }
267    
268            @Override
269            public void deleteGroupTags(long groupId) throws PortalException {
270                    List<AssetTag> tags = getGroupTags(groupId);
271    
272                    for (AssetTag tag : tags) {
273                            deleteTag(tag);
274                    }
275            }
276    
277            @Override
278            public void deleteTag(AssetTag tag) throws PortalException {
279    
280                    // Entries
281    
282                    List<AssetEntry> entries = assetTagPersistence.getAssetEntries(
283                            tag.getTagId());
284    
285                    // Tag
286    
287                    assetTagPersistence.remove(tag);
288    
289                    // Resources
290    
291                    resourceLocalService.deleteResource(
292                            tag.getCompanyId(), AssetTag.class.getName(),
293                            ResourceConstants.SCOPE_INDIVIDUAL, tag.getTagId());
294    
295                    // Properties
296    
297                    assetTagPropertyLocalService.deleteTagProperties(tag.getTagId());
298    
299                    // Indexer
300    
301                    assetEntryLocalService.reindex(entries);
302            }
303    
304            @Override
305            public void deleteTag(long tagId) throws PortalException {
306                    AssetTag tag = assetTagPersistence.findByPrimaryKey(tagId);
307    
308                    deleteTag(tag);
309            }
310    
311            @Override
312            public List<AssetTag> getEntryTags(long entryId) {
313                    return assetEntryPersistence.getAssetTags(entryId);
314            }
315    
316            @Override
317            public List<AssetTag> getGroupsTags(long[] groupIds) {
318                    List<AssetTag> groupsTags = new ArrayList<AssetTag>();
319    
320                    for (long groupId : groupIds) {
321                            List<AssetTag> groupTags = getGroupTags(groupId);
322    
323                            groupsTags.addAll(groupTags);
324                    }
325    
326                    return groupsTags;
327            }
328    
329            @Override
330            public List<AssetTag> getGroupTags(long groupId) {
331                    return assetTagPersistence.findByGroupId(groupId);
332            }
333    
334            @Override
335            public List<AssetTag> getGroupTags(long groupId, int start, int end) {
336                    return assetTagPersistence.findByGroupId(groupId, start, end);
337            }
338    
339            @Override
340            public int getGroupTagsCount(long groupId) {
341                    return assetTagPersistence.countByGroupId(groupId);
342            }
343    
344            @Override
345            public List<AssetTag> getSocialActivityCounterOffsetTags(
346                    long groupId, String socialActivityCounterName, int startOffset,
347                    int endOffset) {
348    
349                    int startPeriod = SocialCounterPeriodUtil.getStartPeriod(startOffset);
350                    int endPeriod = SocialCounterPeriodUtil.getEndPeriod(endOffset);
351    
352                    return getSocialActivityCounterPeriodTags(
353                            groupId, socialActivityCounterName, startPeriod, endPeriod);
354            }
355    
356            @Override
357            public List<AssetTag> getSocialActivityCounterPeriodTags(
358                    long groupId, String socialActivityCounterName, int startPeriod,
359                    int endPeriod) {
360    
361                    int offset = SocialCounterPeriodUtil.getOffset(endPeriod);
362    
363                    int periodLength = SocialCounterPeriodUtil.getPeriodLength(offset);
364    
365                    return assetTagFinder.findByG_N_S_E(
366                            groupId, socialActivityCounterName, startPeriod, endPeriod,
367                            periodLength);
368            }
369    
370            @Override
371            public AssetTag getTag(long tagId) throws PortalException {
372                    return assetTagPersistence.findByPrimaryKey(tagId);
373            }
374    
375            @Override
376            public AssetTag getTag(long groupId, String name) throws PortalException {
377                    return assetTagFinder.findByG_N(groupId, name);
378            }
379    
380            @Override
381            public long[] getTagIds(long groupId, String[] names)
382                    throws PortalException {
383    
384                    List<Long> tagIds = new ArrayList<Long>(names.length);
385    
386                    for (String name : names) {
387                            try {
388                                    AssetTag tag = getTag(groupId, name);
389    
390                                    tagIds.add(tag.getTagId());
391                            }
392                            catch (NoSuchTagException nste) {
393                            }
394                    }
395    
396                    return ArrayUtil.toArray(tagIds.toArray(new Long[tagIds.size()]));
397            }
398    
399            @Override
400            public long[] getTagIds(long[] groupIds, String name)
401                    throws PortalException {
402    
403                    List<Long> tagIds = new ArrayList<Long>(groupIds.length);
404    
405                    for (long groupId : groupIds) {
406                            try {
407                                    AssetTag tag = getTag(groupId, name);
408    
409                                    tagIds.add(tag.getTagId());
410                            }
411                            catch (NoSuchTagException nste) {
412                            }
413                    }
414    
415                    return ArrayUtil.toArray(tagIds.toArray(new Long[tagIds.size()]));
416            }
417    
418            @Override
419            public long[] getTagIds(long[] groupIds, String[] names)
420                    throws PortalException {
421    
422                    long[] tagsIds = new long[0];
423    
424                    for (long groupId : groupIds) {
425                            tagsIds = ArrayUtil.append(tagsIds, getTagIds(groupId, names));
426                    }
427    
428                    return tagsIds;
429            }
430    
431            @Override
432            public String[] getTagNames() {
433                    return getTagNames(getTags());
434            }
435    
436            @Override
437            public String[] getTagNames(long classNameId, long classPK) {
438                    return getTagNames(getTags(classNameId, classPK));
439            }
440    
441            @Override
442            public String[] getTagNames(String className, long classPK) {
443                    return getTagNames(getTags(className, classPK));
444            }
445    
446            @Override
447            public List<AssetTag> getTags() {
448                    return assetTagPersistence.findAll();
449            }
450    
451            @Override
452            public List<AssetTag> getTags(long classNameId, long classPK) {
453                    AssetEntry entry = assetEntryPersistence.fetchByC_C(
454                            classNameId, classPK);
455    
456                    if (entry == null) {
457                            return Collections.emptyList();
458                    }
459    
460                    return assetEntryPersistence.getAssetTags(entry.getEntryId());
461            }
462    
463            @Override
464            public List<AssetTag> getTags(long groupId, long classNameId, String name) {
465                    return assetTagFinder.findByG_C_N(
466                            groupId, classNameId, name, QueryUtil.ALL_POS, QueryUtil.ALL_POS,
467                            null);
468            }
469    
470            @Override
471            public List<AssetTag> getTags(
472                    long groupId, long classNameId, String name, int start, int end) {
473    
474                    return assetTagFinder.findByG_C_N(
475                            groupId, classNameId, name, start, end, null);
476            }
477    
478            @Override
479            @ThreadLocalCachable
480            public List<AssetTag> getTags(String className, long classPK) {
481                    long classNameId = classNameLocalService.getClassNameId(className);
482    
483                    return getTags(classNameId, classPK);
484            }
485    
486            @Override
487            public int getTagsSize(long groupId, long classNameId, String name) {
488                    return assetTagFinder.countByG_C_N(groupId, classNameId, name);
489            }
490    
491            @Override
492            public boolean hasTag(long groupId, String name) throws PortalException {
493                    try {
494                            getTag(groupId, name);
495    
496                            return true;
497                    }
498                    catch (NoSuchTagException nste) {
499                            return false;
500                    }
501            }
502    
503            @Override
504            public AssetTag incrementAssetCount(long tagId, long classNameId)
505                    throws PortalException {
506    
507                    AssetTag tag = assetTagPersistence.findByPrimaryKey(tagId);
508    
509                    tag.setAssetCount(tag.getAssetCount() + 1);
510    
511                    assetTagPersistence.update(tag);
512    
513                    assetTagStatsLocalService.updateTagStats(tagId, classNameId);
514    
515                    return tag;
516            }
517    
518            @Override
519            public void mergeTags(
520                            long fromTagId, long toTagId, boolean overrideProperties)
521                    throws PortalException {
522    
523                    List<AssetEntry> entries = assetTagPersistence.getAssetEntries(
524                            fromTagId);
525    
526                    assetTagPersistence.addAssetEntries(toTagId, entries);
527    
528                    List<AssetTagProperty> tagProperties =
529                            assetTagPropertyPersistence.findByTagId(fromTagId);
530    
531                    for (AssetTagProperty fromTagProperty : tagProperties) {
532                            AssetTagProperty toTagProperty =
533                                    assetTagPropertyPersistence.fetchByT_K(
534                                            toTagId, fromTagProperty.getKey());
535    
536                            if (overrideProperties && (toTagProperty != null)) {
537                                    toTagProperty.setValue(fromTagProperty.getValue());
538    
539                                    assetTagPropertyPersistence.update(toTagProperty);
540                            }
541                            else if (toTagProperty == null) {
542                                    fromTagProperty.setTagId(toTagId);
543    
544                                    assetTagPropertyPersistence.update(fromTagProperty);
545                            }
546                    }
547    
548                    deleteTag(fromTagId);
549            }
550    
551            @Override
552            public List<AssetTag> search(
553                    long groupId, String name, String[] tagProperties, int start, int end) {
554    
555                    return search(new long[] {groupId}, name, tagProperties, start, end);
556            }
557    
558            @Override
559            public List<AssetTag> search(
560                    long[] groupIds, String name, String[] tagProperties, int start,
561                    int end) {
562    
563                    return assetTagFinder.findByG_N_P(
564                            groupIds, name, tagProperties, start, end, null);
565            }
566    
567            @Override
568            public AssetTag updateTag(
569                            long userId, long tagId, String name, String[] tagProperties,
570                            ServiceContext serviceContext)
571                    throws PortalException {
572    
573                    // Tag
574    
575                    AssetTag tag = assetTagPersistence.findByPrimaryKey(tagId);
576    
577                    String oldName = tag.getName();
578    
579                    tag.setModifiedDate(new Date());
580    
581                    name = name.trim();
582                    name = StringUtil.toLowerCase(name);
583    
584                    if (tagProperties == null) {
585                            tagProperties = new String[0];
586                    }
587    
588                    if (!name.equals(tag.getName()) && hasTag(tag.getGroupId(), name)) {
589                            throw new DuplicateTagException(
590                                    "A tag with the name " + name + " already exists");
591                    }
592    
593                    if (!tag.getName().equals(name)) {
594                            try {
595                                    AssetTag existingAssetTag = getTag(tag.getGroupId(), name);
596    
597                                    if (existingAssetTag.getTagId() != tagId) {
598                                            throw new DuplicateTagException(
599                                                    "A tag with the name " + name + " already exists");
600                                    }
601                            }
602                            catch (NoSuchTagException nste) {
603                            }
604                    }
605    
606                    validate(name);
607    
608                    tag.setName(name);
609    
610                    assetTagPersistence.update(tag);
611    
612                    // Properties
613    
614                    List<AssetTagProperty> oldTagProperties =
615                            assetTagPropertyPersistence.findByTagId(tagId);
616    
617                    for (AssetTagProperty tagProperty : oldTagProperties) {
618                            assetTagPropertyLocalService.deleteTagProperty(tagProperty);
619                    }
620    
621                    for (int i = 0; i < tagProperties.length; i++) {
622                            String[] tagProperty = StringUtil.split(
623                                    tagProperties[i],
624                                    AssetTagConstants.PROPERTY_KEY_VALUE_SEPARATOR);
625    
626                            if (tagProperty.length <= 1) {
627                                    tagProperty = StringUtil.split(
628                                            tagProperties[i], CharPool.COLON);
629                            }
630    
631                            String key = StringPool.BLANK;
632    
633                            if (tagProperty.length > 0) {
634                                    key = GetterUtil.getString(tagProperty[0]);
635                            }
636    
637                            String value = StringPool.BLANK;
638    
639                            if (tagProperty.length > 1) {
640                                    value = GetterUtil.getString(tagProperty[1]);
641                            }
642    
643                            if (Validator.isNotNull(key)) {
644                                    assetTagPropertyLocalService.addTagProperty(
645                                            userId, tagId, key, value);
646                            }
647                    }
648    
649                    // Indexer
650    
651                    if (!oldName.equals(name)) {
652                            List<AssetEntry> entries = assetTagPersistence.getAssetEntries(
653                                    tag.getTagId());
654    
655                            assetEntryLocalService.reindex(entries);
656                    }
657    
658                    return tag;
659            }
660    
661            protected String[] getTagNames(List<AssetTag>tags) {
662                    return ListUtil.toArray(tags, AssetTag.NAME_ACCESSOR);
663            }
664    
665            protected void validate(String name) throws PortalException {
666                    if (!AssetUtil.isValidWord(name)) {
667                            throw new AssetTagException(
668                                    StringUtil.merge(
669                                            AssetUtil.INVALID_CHARACTERS, StringPool.SPACE),
670                                    AssetTagException.INVALID_CHARACTER);
671                    }
672            }
673    
674    }