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