'How to find pages with tag?
JSONArray pagesArrayFromMethod = new JSONArray();
private void getListOfChildPagesWithTagAsJSON(Page page) {
try {
Iterator<Page> childPages = page.listChildren();
while (childPages.hasNext()) {
Page childPage = childPages.next();
JSONObject pageObject = new JSONObject();
if (Arrays.asList(childPage.getTags()).contains("customtag")) { // here is problem
pageObject.put(childPage.getTitle(), childPage.getPath());
this.pagesArrayFromMethod.put(pageObject);
}
Iterator<Page> childPagesOfChildpage = childPage.listChildren();
while (childPagesOfChildpage.hasNext()) {
getListOfChildPagesWithTagAsJSON(childPagesOfChildpage.next());
}
}
} catch (JSONException e) {
LOG.error(e.getMessage(), e);
}
}
problem = 'List' may not contain objects of type 'String'!
I have a tag and if the page has this tag it should be put in an array. But when I try to determine if there is a tag on the page, I get an error, I cannot use the method contain with String. I need to convert String into Tag or what method should I use?
Solution 1:[1]
The Page APIs getTags() method returns a Tag[] and not a String[] and hence you can't use contains() method directly.
There are a few options though.
- Find whether the tag is present by looping through your
Tag[]
Tag[] tags = childPage.getTags();
for (Tag tag : tags) {
if ("customtag".equals(tag.getTitle())) { //Replace getTitle with getName or getTagID depending on whatever customtag refers to
pageObject.put(childPage.getTitle(), childPage.getPath());
this.pagesArrayFromMethod.put(pageObject);
break;
}
}
- Alernatively, you can resolve the actual tag using the TagManager API if you have the tag ID or tag title and then use your existing logic. For e.g.
Tag tag = tagManager.resolve("customtag"); //or resolveByTitle() if you only know the title of the tag.
if (tag !=null && Arrays.asList(childPage.getTags()).contains(tag)) {
pageObject.put(childPage.getTitle(), childPage.getPath());
this.pagesArrayFromMethod.put(pageObject);
}
Please note that you need to inject the TagManager to your method to do this. You can get the TagManager from the resource resolver as shown below
TagManager tagManager = resourceResolver.adaptTo(TagManager.class);
- You can also find all content tagged with a particular tag or a set of tags using the TagManager API. However, please note that this would return all the nodes which contains a
cq:tagsproperty and not just thejcr:contentnode. Hence, you may need to further filter from the results.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rakhi4110 |
