April 27, 2020
Estimated Post Reading Time ~

How to create the page through Java API in AEM

This post will explain how to create a page through Java API in Adobe Experience Manager(AEM)

Create the API service
This service create a sample page in Adobe Experience Manager(AEM).

import javax.jcr.Node;
import javax.jcr.Session;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.service.component.ComponentContext;

import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;

@Component(immediate = true, label = "Create Page Service", description = "Create Sample Page", metatype = true)
@Service(value = CreateSamplePage.class )
public class CreateSamplePage {

@Reference
private ResourceResolverFactory resolverFactory;
private ResourceResolver resourceResolver;

private void createPage() throws Exception {
String path="/content/poc";
String pageName="samplePage";
String pageTitle="Sample Page";
String template="/apps/geometrixx/templates/homepage";
String renderer="geometrixx/components/homepage";

this.resourceResolver = this.resolverFactory.getAdministrativeResourceResolver(null);
Page prodPage = null;
Session session = this.resourceResolver.adaptTo(Session.class);
try {
if (session != null) {

// Create Page
PageManager pageManager = this.resourceResolver.adaptTo(PageManager.class);
prodPage = pageManager.create(path, pageName, template, pageTitle);
Node pageNode = prodPage.adaptTo(Node.class);

Node jcrNode = null;
if (prodPage.hasContent()) {

jcrNode = prodPage.getContentResource().adaptTo(Node.class);
} else {
jcrNode = pageNode.addNode("jcr:content", "cq:PageContent");
}
jcrNode.setProperty("sling:resourceType", renderer);


Node parNode = jcrNode.addNode("par");
parNode.setProperty("sling:resourceType", "foundation/components/parsys");

Node textNode = parNode.addNode("text");
textNode.setProperty("sling:resourceType", "foundation/components/text");
textNode.setProperty("textIsRich", "true");
textNode.setProperty("text", "Test page");

session.save();
session.refresh(true);
}

} catch (Exception e) {
throw e;
}
}
}






By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.