Saturday, 10 June 2023

Generic Code snippets

Code Snippets


Creating a resource resolver

public interface ResourceResolverService {

    public ResourceResolver getResourceResolver() throws LoginException;
}
Creating a service
@Component(service = ResourceResolverService.class, immediate = true)
public class ResourceResolverServiceImpl implements ResourceResolverService {
    private static final String SYSTEM_USER = "practiceService";
    @Reference
    ResourceResolverFactory resourceResolverFactory;
    @Override
    public ResourceResolver getResourceResolver() throws LoginException {
        Map<String, Object> param = new HashMap<>();
        param.put(ResourceResolverFactory.SUBSERVICE, SYSTEM_USER);
        return resourceResolverFactory.getServiceResourceResolver(param);
    }

}

Using it in another class.
@Reference
ResourceResolverService resourceResolverService;
try (ResourceResolver resourceResolver = resourceResolverService.getResourceResolver()) {
    // Code Implementation
} catch (Exception e) {
    LOGGER.error("Exception occurred: {}", e.getMessage());
}

OSGi configurations

configuration name : org.apache.sling.serviceusermapping.impl.ServiceUserMapperImpl.practice.xml
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
   xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="sling:OsgiConfig"
    service.ranking="100"
    user.mapping="[practice.core:practiceService\=practiceuser]"/>


Updating Node in CRX repository

Method 1, Programmatically Update AEM JCR nodes in JAVA with org.apache.sling.api.resource.ModifiableValueMap

@Reference
ResourceResolverService resourceResolverService;
try (ResourceResolver resolver = resourceResolverService.getResourceResolver()) {
    Resource resource = resolver.getResource("/content/sourcedcode/jcr:content");
    if (Objects.nonNull(resource)) {
        ModifiableValueMap map = resource.adaptTo(ModifiableValueMap.class);
        map.put("newProperty", "value");
        map.put("existingProperty", "value");
        map.remove("existingProperty"); //remove
        resolver.commit();
    }
} catch (Exception e) {
    e.printStackTrace();
}

Method 2, Programmatically Update AEM JCR nodes in JAVA with
javax.jcr.Node

@Reference
ResourceResolverService resourceResolverService;
try (ResourceResolver resolver = resourceResolverService.getResourceResolver()) {
    Session session = resolver.adaptTo(Session.class);
    Node contentNode = session.getNode("/content/sourcedcode/jcr:content");
    if (Objects.nonNull(contentNode)) {
        contentNode.setProperty("newProperty", "value");
        contentNode.setProperty("existingProperty", "value");
        contentNode.setProperty("existingProperty", (Value)null); //remove
        session.save();
    }
} catch (Exception e) {
    e.printStackTrace();
}


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;
  @Reference
  private ResourceResolverService resourceResolverService;
  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 = resourceResolverService.getResourceResolver();
    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;
    }
  }
}

Update page properties using ValueMap


import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;

public class PagePropertiesUpdater {

    private ResourceResolver resourceResolver;

    public void updatePageProperties(String pagePath, String propertyName, String newValue) {
        Resource pageResource = resourceResolver.getResource(pagePath);
        
        if (pageResource != null) {
            ValueMap properties = pageResource.adaptTo(ValueMap.class);
            
            if (properties != null) {
                properties.put(propertyName, newValue);
                resourceResolver.commit();
                System.out.println("Page property updated successfully.");
            } else {
                System.out.println("Failed to adapt page resource to ValueMap.");
            }
        } else {
            System.out.println("Page does not exist.");
        }
    }
}

Tuesday, 6 June 2023

AEM Project Creation Issues

 AEM Project Creation issues


AEM Project archetype and AEM version combinations

Source : https://github.com/adobe/aem-project-archetype/blob/develop/VERSIONS.md 


Archetype VersionAEM Version
76.0 or newer
86.0 or newer
96.0 or newer
106.0 or newer
116.2 or newer
126.3 or newer
146.4, 6.3 + SP2
156.4, 6.3 + SP2
166.4, 6.3 + SP2
136.4, 6.3 + SP2
176.4, 6.3 + SP2
186.5, 6.4, 6.3 + SP3
196.5, 6.4, 6.3 + SP3
20, 21, 226.5, 6.4, 6.3 + SP3
236.5, 6.4, 6.3 + SP3, AEM as a Cloud Service
24, 25, 26, 276.5.5, 6.4.8.1, AEM as a Cloud Service
28, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41
6.5.7, AEM as a Cloud Service


React SPA 

mvn -B archetype:generate -D archetypeGroupId=com.adobe.aem -D archetypeArtifactId=aem-project-archetype -D archetypeVersion=35 -D appTitle="Agro Tourism" -D appId="agrotourism" -D groupId="com.agro.tourism.aem" -D artifactId="agrotourism-aem-project" -D version="0.0.1-SNAPSHOT" -D aemVersion="6.5.5" -D includeDispatcherConfig=n -D includeExamples=n  -D frontendmodule=react


error 1

[ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.12.0:npm (npm run prod) on project agrotourism-aem-project.ui.frontend: Failed to run task: 'npm run prod' failed. org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1) -> [Help 1]


Solution 1 : To fix this, set the version of POM.xml NODE and NPM version to that of local node and npm versions.


Solution 2 : make changes in package.json file in ui.frontend

update "typescript":"3.3.3333 to "typescript":" 4.8.2"

remove package-lock.json


error 2
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.2.1:generate (default-cli) on project standalone-pom: startup failed:
[ERROR] General error during conversion: Conflicting module versions. Module [groovy-all is loaded in version 2.4.16 and you are trying to load version 2.4.8

Solution 1 : update the groovy version to 2.4.8 of the pom.xml
.m2/repository/org/apache/maven/archetype/archetype-common/3.2.1/archetype-common-3.2.1.pom:      <version>2.4.16</version>



Note : If targeting AEM 6.5.5+ replace aemVersion="cloud" with aemVersion="6.5.5". If targeting 6.4.8+, use aemVersion="6.4.8".

Dispatcher configurations in AEM - 2

 Dispatcher configuration 1. The Dispatcher configuration is stored in the dispatcher.any text file. 2. The file contains a series of single...