Here, we will show you how to create a page using PageManager interface, I am using system user account to get access to resource resolver, you can refer my other article on how to create system user in AEM
This is just code snippet we are not going to explain any concept out here

package com.aem.toolkit.core.models;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.Session;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import com.adobe.cq.sightly.WCMUsePojo;
import com.day.cq.commons.jcr.JcrConstants;
import com.day.cq.wcm.api.Page;
public class PageHelper extends WCMUsePojo {
	public String getUserName() {
		return user;
	}
	String user = "";
	public void getCreatePage() throws LoginException {
		String pagePath = "/content/toolkit/en/";
		String pageName = "home";
		String templatePath = "/apps/toolkit/templates/page-home";
		String pageTitle = "keysandstrokes home page";
		Page newPage;
		ResourceResolverFactory resourceResolverFactory = getSlingScriptHelper()
				.getService(ResourceResolverFactory.class);
		Map<String, Object> authInfo = new HashMap<>();
		authInfo.put(ResourceResolverFactory.SUBSERVICE, "createService");
		ResourceResolver resolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
		Session session = resolver.adaptTo(Session.class);
		try {
			newPage = getPageManager().create(pagePath, pageName, templatePath, pageTitle);
			if (newPage != null) {
				user = resolver.getUserID();
				Node newNode = newPage.adaptTo(Node.class);
				Node cont = newNode.getNode("jcr:content");
				if (cont != null) {
					Node rootNode = session.getRootNode();
					String path = rootNode.getPath();
					Node parNode = JcrUtils.getNodeIfExists(cont, "par");
					Node imageNode = JcrUtils.getOrCreateByPath(parNode.getPath() + "/image",
							JcrConstants.NT_UNSTRUCTURED, session);
					Node textNode = JcrUtils.getNodeIfExists(parNode, "text");
					imageNode.setProperty("sling:resourceType", "foundation/components/image");
					imageNode.setProperty("fileReference", "/content/dam/we-retail-screens/we-retail-instore-logo.png");
					textNode.setProperty("text", "<p>This page is created using page manager</p>");
					session.save();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public void activate() throws Exception {
	}
}

 
 
 

By coderss

Leave a Reply

Your email address will not be published. Required fields are marked *