Expand my Community achievements bar.

SOLVED

Easy way to create page from JSON string

Avatar

Level 3

A third party tool will upload a JSON file with the required data into the DAM. Based on the provided page details from JSON, such as page_path, page_name, and other configurations, a page needs to be created.

Will PageManager support creating all the nodes in the JSON? How?

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

To create a page in AEM using the PageManager API in Java, you need to follow these steps:

  1. Parse the JSON file to extract the necessary details.
  2. Use the AEM APIs to create a new page in the.

 

Here is an example code snippet that demonstrates how to achieve this:

 

PageCreationService.java : create an OSGi service for handling the page creation logic.

import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.api.PageManagerFactory;
import com.day.cq.wcm.api.WCMException;
import com.google.gson.JsonObject;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import java.util.HashMap;
import java.util.Map;

@Component(service = PageCreationService.class)
public class PageCreationService {

    @reference
    private ResourceResolverFactory resourceResolverFactory;

    @reference
    private PageManagerFactory pageManagerFactory;

    public void createPageFromJson(JsonObject jsonObject) throws PersistenceException, LoginException {
        ResourceResolver resourceResolver = null;
        try {
            Map<String, Object> param = new HashMap<>();
            param.put(ResourceResolverFactory.SUBSERVICE, "writeService");
            resourceResolver = resourceResolverFactory.getServiceResourceResolver(param);

            String pagePath = jsonObject.get("page_path").getAsString();
            String pageName = jsonObject.get("page_name").getAsString();
            String pageTemplate = jsonObject.get("page_template").getAsString();
            String pageTitle = jsonObject.get("page_title").getAsString();

            createPage(resourceResolver, pagePath, pageName, pageTemplate, pageTitle);
        } finally {
            if (resourceResolver != null && resourceResolver.isLive()) {
                resourceResolver.close();
            }
        }
    }

    private void createPage(ResourceResolver resourceResolver, String pagePath, String pageName, String pageTemplate, String pageTitle) throws PersistenceException {
        PageManager pageManager = pageManagerFactory.getPageManager(resourceResolver);

        try {
            Page page = pageManager.create(pagePath, pageName, pageTemplate, pageTitle);
            if (page != null) {
                System.out.println("Page created successfully at: " + page.getPath());
            } else {
                System.out.println("Failed to create page at: " + pagePath + "/" + pageName);
            }
        } catch (WCMException e) {
            throw new PersistenceException("Error creating page: " + e.getMessage(), e);
        }
    }
}

 

PageCreationServlet.java: create a Sling servlet to call the PageCreationService.

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.servlets.annotations.SlingServletPaths;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.LoginException;

import javax.servlet.Servlet;
import java.io.BufferedReader;
import java.io.IOException;

@Component(service = { Servlet.class })
@SlingServletPaths("/bin/createPage")
public class PageCreationServlet extends SlingAllMethodsServlet {

    @reference
    private PageCreationService pageCreationService;

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
        BufferedReader reader = request.getReader();
        JsonObject jsonObject = JsonParser.parseReader(reader).getAsJsonObject();

        try {
            pageCreationService.createPageFromJson(jsonObject);
            response.setStatus(SlingHttpServletResponse.SC_OK);
            response.getWriter().write("Page creation initiated.");
        } catch (PersistenceException | LoginException e) {
            response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error creating page: " + e.getMessage());
        }
    }
}

 

 

Note: This is non tested example code with hardcoded values. You may need to refactor it further, make it configurable, and adapt it according to your business logic.



Arun Patidar

View solution in original post

4 Replies

Avatar

Community Advisor

@Nilesh_Mali  I think pagemanager can create a page only with a page template. For the content inside that page you will have to write a custom code that allows you to parse the json into specific components assuming you have all those components in your component catalog.

Avatar

Correct answer by
Community Advisor

To create a page in AEM using the PageManager API in Java, you need to follow these steps:

  1. Parse the JSON file to extract the necessary details.
  2. Use the AEM APIs to create a new page in the.

 

Here is an example code snippet that demonstrates how to achieve this:

 

PageCreationService.java : create an OSGi service for handling the page creation logic.

import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.api.PageManagerFactory;
import com.day.cq.wcm.api.WCMException;
import com.google.gson.JsonObject;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import java.util.HashMap;
import java.util.Map;

@Component(service = PageCreationService.class)
public class PageCreationService {

    @reference
    private ResourceResolverFactory resourceResolverFactory;

    @reference
    private PageManagerFactory pageManagerFactory;

    public void createPageFromJson(JsonObject jsonObject) throws PersistenceException, LoginException {
        ResourceResolver resourceResolver = null;
        try {
            Map<String, Object> param = new HashMap<>();
            param.put(ResourceResolverFactory.SUBSERVICE, "writeService");
            resourceResolver = resourceResolverFactory.getServiceResourceResolver(param);

            String pagePath = jsonObject.get("page_path").getAsString();
            String pageName = jsonObject.get("page_name").getAsString();
            String pageTemplate = jsonObject.get("page_template").getAsString();
            String pageTitle = jsonObject.get("page_title").getAsString();

            createPage(resourceResolver, pagePath, pageName, pageTemplate, pageTitle);
        } finally {
            if (resourceResolver != null && resourceResolver.isLive()) {
                resourceResolver.close();
            }
        }
    }

    private void createPage(ResourceResolver resourceResolver, String pagePath, String pageName, String pageTemplate, String pageTitle) throws PersistenceException {
        PageManager pageManager = pageManagerFactory.getPageManager(resourceResolver);

        try {
            Page page = pageManager.create(pagePath, pageName, pageTemplate, pageTitle);
            if (page != null) {
                System.out.println("Page created successfully at: " + page.getPath());
            } else {
                System.out.println("Failed to create page at: " + pagePath + "/" + pageName);
            }
        } catch (WCMException e) {
            throw new PersistenceException("Error creating page: " + e.getMessage(), e);
        }
    }
}

 

PageCreationServlet.java: create a Sling servlet to call the PageCreationService.

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.servlets.annotations.SlingServletPaths;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.LoginException;

import javax.servlet.Servlet;
import java.io.BufferedReader;
import java.io.IOException;

@Component(service = { Servlet.class })
@SlingServletPaths("/bin/createPage")
public class PageCreationServlet extends SlingAllMethodsServlet {

    @reference
    private PageCreationService pageCreationService;

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
        BufferedReader reader = request.getReader();
        JsonObject jsonObject = JsonParser.parseReader(reader).getAsJsonObject();

        try {
            pageCreationService.createPageFromJson(jsonObject);
            response.setStatus(SlingHttpServletResponse.SC_OK);
            response.getWriter().write("Page creation initiated.");
        } catch (PersistenceException | LoginException e) {
            response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Error creating page: " + e.getMessage());
        }
    }
}

 

 

Note: This is non tested example code with hardcoded values. You may need to refactor it further, make it configurable, and adapt it according to your business logic.



Arun Patidar

Avatar

Community Advisor

Hi @Nilesh_Mali ,

 

Yes, On high level its possible to create pages using the JSON data read from DAM using Page Manager API.

However, you need to create Page Templates before using pagemanager api. as you dont have resourceresolver at this point for using Page Builder API.

Here are some steps for your reference.

1.Create Page Templates as required.

2. Create a Service class that reads JSON data & extract useful information to create Page, such as page path, page name, template & title.(follow this link & use create method https://developer.adobe.com/experience-manager/reference-materials/6-4/javadoc/com/day/cq/wcm/api/Pa...)

3. Now, you should be having a page created at desired path & you can get Resource resolver.

4. Fill data from JSON onto this page jcr node by using Sling API. for example : 

Iterator<Resource> resourcesIterator = resourceResolver .findResources(QUERY_STRING, Query.JCR_SQL2); while (resourcesIterator.hasNext()) { Resource resource = resourcesIterator.next(); yourmethod(resource); }

5.Avoid using JCR api unless only to create an Event on Node. 

 

 

Hope this helps;

Aditya Chabuku

Thanks,

Aditya Chabuku

Avatar

Level 4

Hi @Nilesh_Mali 

Yes, PageManager can support creating all the nodes in the JSON. To achieve this, you can parse the JSON file and extract the required page details such as page_path, page_name, and other configurations.

Here is an example of how you can do it in Java:

import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import org.json.JSONObject;

// Assume you have a JSON string
String jsonString = "...";

// Parse the JSON string
JSONObject jsonObject = new JSONObject(jsonString);

// Get the page details from the JSON object
String pagePath = jsonObject.getString("page_path");
String pageName = jsonObject.getString("page_name");
//...

// Create a PageManager instance
PageManager pageManager = getPageManagerInstance();

// Create a new page
Page page = pageManager.create(pagePath, pageName, "...");

// Create child nodes based on the JSON data
//...

 

In the above example, we first parse the JSON string using a JSON library such as org.json. Then, we extract the required page details from the JSON object. We create a PageManager instance and use it to create a new page with the extracted details. Finally, we can create child nodes based on the JSON data.

Note that the above code is just an example and you may need to modify it to fit your specific requirements. Additionally, you may need to handle errors and exceptions properly.