Search code examples
osgimaven-3aemjcrsling

Issue with importing JcrTagImpl class in OSGI


I need to import JcrTagImpl class which is located in CQ Day Communique 5 Tagging jar file(com.day.cq.cq-tagging)

Then I tried to add the above jar in my pom.xml's dependency as below then I can import the whole package as com.day.cq.tagging.*;

<dependency>
    <groupId>com.day.cq</groupId>
    <artifactId>cq-tagging</artifactId>
    <version>5.7.18</version>
    <scope>provided</scope>
</dependency>

UPDATE:
I need to call getTagID method which is located in com.day.cq.tagging.JcrTagImpl class. AEM uses com.day.cq.tagging.TagCommandServlet to display the TagID in tagging console. TagCommandServlet is importing JcrTagImpl class and calling getTagID method.

I have my own servlet and I wanted to call getTagID. I could not call directly getTagID of JcrTagImpl implementation since it is not exposed. Can it done by any annotation?Can you please guide me how to call getTagId method.


Solution

  • You are trying to call the implementation directly instead of the service. Generally, the implementation is not exposed and you would have to use the service instead.

    I guess, TagManager is available as a Sling Service, using which you can work on Tags. Use @Reference to inject it in your service or use sling.adaptTo() to adapt your resource.

    EDIT:

    Like i mentioned earlier, you cannot access an implementation class directly, as it wouldn't be exported by the bundle.

    However to get the tag ID you can use any of the below methods according to your requirements.

    1. If you have the path to the tag, you can get the resource and adaptTo Tag.class and retrieve the tagID
    2. You can adaptTo TagManager.class from a ResourceResolver object and then resolve the path of the tag to get the Tag object
    3. Use the JcrTagManagerFactory service to obtain the tag manager and then resolve the path of the tag.

    @SlingServlet({ //config }) public class MyServlet extends SlingSafeMethodsServlet {

    @Reference
    private JcrTagManagerFactory jcrTagManagerFactory;
    
    protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse res) {
        //First Method
        ResourceResolver resolver = req.getResourceResolver();
        Resource tagResource = resolver.resolve("<<path to the tag>>");
        Tag tag1 = tagResource.adaptTo(Tag.class);
        tag1.getTagID();
    
        //Second Method
        TagManager tagManager = resolver.adaptTo(TagManager.class);
        Tag tag2 = tagManager.resolve("<<path to tag>>");
        tag2.getTagID();
    
        //Third Approach
        Session session = resolver.adaptTo(Session.class);
        TagManager tagManager = jcrTagManagerFactory.getTagManager(session);
        Tag tag3 = tagManager.resolve("<<path to tag>>");
        tag3.getTagID();
    }
    

    }

    Using the TagManager, you can fetch the tags set on the current resource or query for tags etc.