adding child properties to the parent node via java code | Community
Skip to main content
Level 2
November 22, 2023
Solved

adding child properties to the parent node via java code

  • November 22, 2023
  • 4 replies
  • 2228 views

i need to add email address from all child nodes that are having, to the parent node but I'm unable to replicate my changes . my changes are not reflcting in the aem node . this is the code I'm using . ive installed the folder node from the package manager.

package com.cni.cq.dam.ui.contactsheet.service;

 

import org.apache.sling.api.resource.LoginException;

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

import org.apache.sling.api.resource.ResourceResolverFactory;

import org.apache.sling.jcr.api.SlingRepository;

import org.osgi.service.component.annotations.Component;

import org.osgi.service.component.annotations.Reference;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

import com.cni.cq.dam.core.assetbinary.AssetBinaryService;

import com.cni.cq.dam.core.publications.PublicationsService;

 

import java.util.HashMap;

import java.util.Map;

 

import javax.jcr.Node;

import javax.jcr.NodeIterator;

import javax.jcr.RepositoryException;

import javax.jcr.Session;

import javax.jcr.Value;

import javax.jcr.ValueFactory;

 

@8220494(immediate = true, service = UpdateEmailsService.class)

public class UpdateEmailsService {

 

    private static final Logger log = LoggerFactory.getLogger(UpdateEmailsService.class);

 

    @3214626

   ResourceResolverFactory resolverFactory;

 

     @3214626

    private XMLHandler xmlHandler;

    

    @3214626

    PublicationsService publicationService;

    

    @3214626

    AssetBinaryService assetBinaryService;

 

    @3214626

    SlingRepository slingRepository;

 

static String serviceUser = "shivakumar";

    public static ResourceResolver newResolver(ResourceResolverFactory resourceResolverFactory) throws LoginException {

    final Map<String, Object> paramMap = new HashMap<>();

    paramMap.put(ResourceResolverFactory.SUBSERVICE, serviceUser);

 

    // fetches the admin service resolver using service user.

    ResourceResolver resolver = resourceResolverFactory.getServiceResourceResolver(paramMap);

    return resolver;

}

    public void updateEmails() throws LoginException {

        ResourceResolver resolver = null;

 

        try {

            // Assuming you have a service user with sufficient privileges

            resolver=newResolver(resolverFactory);

            log.debug("Obtained Resource Resolver");

 

            Session session = resolver.adaptTo(Session.class);

 

            // Parent node path

            String parentNodePath = "/content/contracted-creator/g/ethan_james_green";

            Node parentNode = session.getNode(parentNodePath);

 

            log.debug("Got parent node: {}", parentNodePath);

 

            // Create or retrieve the "emails" property in the parent node

            ValueFactory valueFactory = session.getValueFactory();

            Value[] existingEmailsValue = parentNode.hasProperty("emailId")

                    ? parentNode.getProperty("emailId").getValues()

                    : new Value[0];

 

            log.debug("Existing emails count: {}", existingEmailsValue.length);

 

            // Create an array to store the updated email values

            Value[] updatedEmailsValue = new Value[existingEmailsValue.length];

 

            // Iterate through child nodes

            NodeIterator childNodes = parentNode.getNodes();

            int i = 0;

            while (childNodes.hasNext()) {

                Node childNode = childNodes.nextNode();

                if (childNode.hasProperty("emailId")) {

                    Value emailValue = childNode.getProperty("emailId").getValue();

 

                    // Add the email value to the array

                    updatedEmailsValue[i++] = emailValue;

                }

            }

 

            // Update the "emails" property in the parent node

            parentNode.setProperty("emailId", updatedEmailsValue);

 

            // Save changes

            session.save();

        } catch (RepositoryException e) {

            log.error("Error updating emailId", e);

        } finally {

            if (resolver != null && resolver.isLive()) {

                resolver.close();

            }

        }

    }

}

 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by EstebanBustamante

As everyone has already pointed out, you must check the logs to find what is the issue with your code, the code should do the work (although you could clean up a little bit), but most likely there is an issue either with the User not being able to login or with the User not having permissions to write in the "some" node you are attempting to write. The only way to understand what's going on is either checking the logs or debugging locally.

 

Please read these articles which explain in detail how to do both things: 

Debug: https://experienceleague.adobe.com/docs/experience-manager-learn/cloud-service/debugging/debugging-aem-sdk/remote-debugging.html?lang=en

Create custom logs and Check logs: https://www.youtube.com/watch?v=9WtiFSY_IFg&ab_channel=AEMandDevopsTutorial 

https://www.youtube.com/watch?v=16wirUIm7BA&ab_channel=AEMandDevopsTutorial 

 

After you successfully check the logs or debug I am sure you will be able to resolve the issue, otherwise post back what you find in the logs

4 replies

Saravanan_Dharmaraj
Community Advisor
Community Advisor
November 24, 2023

@shivanandh Does this service user has write access to that repo path? Did you see any error in the logs?

Level 2
November 24, 2023

I can not see any logs in error.log in log support . i can see my component service in active but it is not relfecting anything . how can i debug this . or where can i see logs for this . please help me 

you can igonre the service user name changing. i have created new one as in the ss

Hemant_arora
Level 8
November 24, 2023

Please see  if your service user is created, and mapping is registered

paramMap.put(ResourceResolverFactory.SUBSERVICE, serviceUser);.

Share logs.

Additionally use ModifiableValumap instead of node api

Level 2
November 24, 2023

hii @hemant_arora    the service user is created and logs i can not see any logs in error.log related to this file . but the service is registering . can you help me how to resolve the replication . 

the above code i have given diff service user . but i created new user and giving you ss. and i have also aletered the code to this user

 

 

 

kautuk_sahni
Community Manager
Community Manager
December 4, 2023

@shivanandh Did you find the suggestions from users helpful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.

Kautuk Sahni
Level 2
December 4, 2023

hii @kautuk_sahni   i havent find the solution yet . you can see my replies to comments im still facing the same issue.

EstebanBustamante
Community Advisor and Adobe Champion
EstebanBustamanteCommunity Advisor and Adobe ChampionAccepted solution
Community Advisor and Adobe Champion
December 4, 2023

As everyone has already pointed out, you must check the logs to find what is the issue with your code, the code should do the work (although you could clean up a little bit), but most likely there is an issue either with the User not being able to login or with the User not having permissions to write in the "some" node you are attempting to write. The only way to understand what's going on is either checking the logs or debugging locally.

 

Please read these articles which explain in detail how to do both things: 

Debug: https://experienceleague.adobe.com/docs/experience-manager-learn/cloud-service/debugging/debugging-aem-sdk/remote-debugging.html?lang=en

Create custom logs and Check logs: https://www.youtube.com/watch?v=9WtiFSY_IFg&ab_channel=AEMandDevopsTutorial 

https://www.youtube.com/watch?v=16wirUIm7BA&ab_channel=AEMandDevopsTutorial 

 

After you successfully check the logs or debug I am sure you will be able to resolve the issue, otherwise post back what you find in the logs

Esteban Bustamante