Expand my Community achievements bar.

SOLVED

adding child properties to the parent node via java code

Avatar

Level 3

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;

 

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

public class UpdateEmailsService {

 

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

 

    @reference

   ResourceResolverFactory resolverFactory;

 

     @reference

    private XMLHandler xmlHandler;

    

    @reference

    PublicationsService publicationService;

    

    @reference

    AssetBinaryService assetBinaryService;

 

    @reference

    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();

            }

        }

    }

}

 

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

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-a...

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

View solution in original post

7 Replies

Avatar

Community Advisor

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

Avatar

Level 3

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

Avatar

Level 8

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

Avatar

Level 3

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

 

 

 

Screenshot 2023-11-24 at 2.11.11 PM.pngScreenshot 2023-11-24 at 2.24.31 PM.png

Avatar

Administrator

@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

Avatar

Level 3

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

Avatar

Correct answer by
Community Advisor

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-a...

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