Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Page object in Java Class using URL

Tags:

aem

In my Java class in an OSGi bundle, I have the URI of a page -

String pageUri = "/content/site/page.html" ;

How can I create a Page object using this URL ? I basically need to fetch the page properties also from the object later on...

I tried this code in my class:

PageManager pm = new PageManager();
Page page = pm.getPage(pageUri);

But this gives me compilation error:

Cannot instantiate the type PageManager
like image 684
Riju Mahna Avatar asked Jan 12 '23 12:01

Riju Mahna


1 Answers

You should be able to inject a ResourceResolverFactory instance into your component/service and from there resolve the Resource/Page as described in Getting Resources and Properties in Sling.

For example:

@Component(immediate = true)
@Service(GetMeAPage.class)
public class GetMeAPage {

    @Reference
    private ResourceResolverFactory resourceResolverFactory;

    private static final String pageUri = "/content/site/page.html";

    /**
     * This method is executed at component startup rather than in the context of a request.
     */
    @Activate
    public void getSpecificPage() {
        ResourceResolver resourceResolver = null;
        try {
            resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
            Page page = getSpecificPage(resourceResolver);
            System.out.println(page.getTitle());
        } catch (LoginException e) {
            e.printStackTrace();
        } finally {
            if (resourceResolver != null) {
                resourceResolver.close();
            }
        }
    }

    public Page getSpecificPage(ResourceResolver resourceResolver) {
        Resource resource = resourceResolver.resolve(pageUri);
        return resource.adaptTo(Page.class);

    }
}

Full code in this gist

This uses an administrative login which is not ideal. I would recommend using the ResourceResolver from the request. The simplest way of doing this is to pass it as a method parameter to getSpecificPage(resourceResolver) (above) from your component/servlet.

Update: The correct way of doing this in more recent versions of Sling (circa 2014, AEM6+) is to use Sling Service Authentication. The getAdministrativeResourceResolver method is now deprecated.

like image 167
diffa Avatar answered Feb 23 '23 21:02

diffa