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