-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmergeDuplicateTags.groovy
71 lines (61 loc) · 2.34 KB
/
mergeDuplicateTags.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
Merge Duplicate Tags in an Application
This was a requirement in one of my client who asked us to merge the Duplicate Tags . This way you can list out all the duplicate tags and merge all of them into the first Master Tag. All the related references in the Pages will automatically be changed as per the API.
/** @author Hashim Khan */
import org.apache.sling.api.resource.Resource
import com.day.cq.tagging.Tag
import org.apache.sling.api.resource.ResourceResolver
import com.day.cq.tagging.TagManager
import javax.jcr.Node;
import java.lang.Thread.*;
def tagLocation = "/etc/tags"
def delay = 10; //in Milliseconds.
def buildQuery(tagLocation) {
def queryManager = session.workspace.queryManager;
def statement = "/jcr:root" + tagLocation + "//element(*, cq:Tag)"
def query = queryManager.createQuery(statement, 'xpath')
}
def findDuplicateTags(tagLocation, tagNodeName) {
def queryManager = session.workspace.queryManager;
def statement = "/jcr:root" + tagLocation + "//element(*, cq:Tag) [fn:name() = '" + tagNodeName + "' ]"
def query = queryManager.createQuery(statement, 'xpath')
}
final def query = buildQuery(tagLocation);
final def result = query.execute()
def tagList = []
result.nodes.each {
node - >
String nodeTitle = node.name;
tagList.add(nodeTitle);
}
def duplicates = tagList.findAll {
tagList.count(it) > 1
}
def uniqueUsers = duplicates.unique(mutate = false)
def count = 0;
TagManager tm = resourceResolver.adaptTo(com.day.cq.tagging.TagManager);
def mergecount = 0;
uniqueUsers.each {
def tagquery = findDuplicateTags(tagLocation, it);
def pathresult = tagquery.execute()
Tag tag, masterTag = null;
count = 0;
pathresult.nodes.each {
node - >
Resource r = resourceResolver.getResource(node.path)
tag = r.adaptTo(com.day.cq.tagging.Tag)
Node tempNode = r.adaptTo(javax.jcr.Node);
if (count == 0) {
masterTag = tag;
} else if (tm != null && !(tag.getPath() == masterTag.getPath())) {
if (!tempNode.hasNodes()) {
println 'Merging Tag :: ' + tag.getPath() + ' into>> ' + masterTag.getPath()
mergecount++
tm.mergeTag(tag, masterTag)
}
}
count++
Thread.currentThread().sleep((long)(delay));
}
}
println 'Merged tags count ::' + mergecount