Expand my Community achievements bar.

SOLVED

get component policy values in servlet

Avatar

Level 4

Component Dialog has "select" drop down that needs to read values set by author in "design dialog".

Following is the servlet that mapped to dialog select field using resourceType mapping. How to get get component policy values in servlet. 

 

I tried below but content resource coming as null 

 

Resource contentResource = resolver.getResource((String) request.getAttribute(Value.CONTENTPATH_ATTRIBUTE));

 

Thanks for any help. Below is the servlet code.

package com.company.aem.core.servlets;

import com.adobe.granite.ui.components.Value;
import com.adobe.granite.ui.components.ds.DataSource;
import com.adobe.granite.ui.components.ds.EmptyDataSource;
import com.adobe.granite.ui.components.ds.SimpleDataSource;
import com.adobe.granite.ui.components.ds.ValueMapResource;
import com.day.cq.wcm.api.policies.ContentPolicy;
import com.day.cq.wcm.api.policies.ContentPolicyManager;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceMetadata;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.api.wrappers.ValueMapDecorator;
import org.osgi.service.component.annotations.Component;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 
 * Data source for links dropdown
 */
@Component(service = { Servlet.class }, property = {
		"sling.servlet.resourceTypes=" + AllowedArticleInsightsLinksServlet.RESOURCE_TYPE, "sling.servlet.methods=GET",
		"sling.servlet.extensions=html" })
public class AllowedArticleInsightsLinksServlet extends SlingSafeMethodsServlet
{

	public final static String RESOURCE_TYPE = "pi-web/components/content/articleinsights/datasource/allowedlinks";

	@Override
	protected void doGet(
			SlingHttpServletRequest request, SlingHttpServletResponse response)
			throws ServletException, IOException
	{
		SimpleDataSource
				allowedHeadingElementsDataSource =
				new SimpleDataSource(getAllowedHeadingElements(request).iterator());
		request.setAttribute(DataSource.class.getName(), allowedHeadingElementsDataSource);
	}

	private List
<
Resource
>
 getAllowedHeadingElements(SlingHttpServletRequest request)
	{
		List
<
Resource
>
 allowedHeadingElements = new ArrayList<>();
		ResourceResolver resolver = request.getResourceResolver();
		Resource contentResource = resolver.getResource((String) request.getAttribute(Value.CONTENTPATH_ATTRIBUTE));
		ContentPolicyManager policyManager = resolver.adaptTo(ContentPolicyManager.class);
		if (policyManager != null && contentResource != null)
		{
			ContentPolicy policy = policyManager.getPolicy(contentResource);
			if (policy != null)
			{
				request.setAttribute(DataSource.class.getName(), EmptyDataSource.instance());

				Resource allowedLinksResource = policy.adaptTo(Resource.class).getChild("links");
				if (allowedLinksResource != null)
				{
					ValueMap vm = null;

					for (Resource rs : allowedLinksResource.getChildren())
					{
						vm = new ValueMapDecorator(new HashMap<>());
						// Specify the value and text values
						String Value = rs.getValueMap().get("linkhref", String.class);
						String Text = rs.getValueMap().get("linkname", String.class);
						//populate the map
						vm.put("value", Value);
						vm.put("text", Text);

						allowedHeadingElements.add(
								new ValueMapResource(resolver, new ResourceMetadata(), "nt:unstructured", vm));
					}
				}

			}
		}
		return allowedHeadingElements;
	}

}
1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @Manjunath_K 

Can get ComponentContext from request.

ContentPolicyManager policyManager = resolver.adaptTo(ContentPolicyManager.class);
ComponentContext componentContxt = (ComponentContext) request.getAttribute("com.day.cq.wcm.componentcontext");
ContentPolicy policy = policyManager.getPolicy(componentContxt);

Hope it works!

AG

View solution in original post

13 Replies

Avatar

Community Advisor

What is the value of (String)request.getAttribute(Value.CONTENTPATH_ATTRIBUTE) when you debug? We can check if its a valid resource path. May be if it has selector or something, we can try resolver.resolve(pathobtained)

Also check if the resolver has correct access, may be we need to use a admin user service resolver

Avatar

Level 4
It is not directly mapped to component but one of component dialog fields. that would we component/cq:dialog/items/item/field

Avatar

Community Advisor
Did you try the comment at https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/get-component-resource-in-... ? Seems like we are getting the node from the component i.e under /apps so try to see if the option of getting the page resource works or using a admin service resolver works

Avatar

Community Advisor

Hi @sreedobe 

Check your request has read access to the content path.

AG

Avatar

Level 8

Hi @sreedobe 

If its resource based servlet then you can access component policy configuration by passing current resource to getPolicy(). in below example component policy configuration has title field & same configured value is retrieved using ContentPolicyManager.

 

ContentPolicyManager policyManager = request.getResourceResolver().adaptTo(ContentPolicyManager.class);
if (policyManager != null) {
ContentPolicy contentPolicy = policyManager.getPolicy(request.getResource()); //ex: request.getResource() path "/content/test-page/jcr:content/root/component"
if (contentPolicy != null) {
String title= contentPolicy.getProperties().get("title",String.class);
}
}

refer this article:

https://techrevel.blog/2017/08/28/aem-template-editor-design-configuration-via-policies/

 

 

Hope this helps!

 

Avatar

Level 4
Here resource is not /component rather "/component/cq_dialog/items/item/field"

Avatar

Correct answer by
Community Advisor

Hi @Manjunath_K 

Can get ComponentContext from request.

ContentPolicyManager policyManager = resolver.adaptTo(ContentPolicyManager.class);
ComponentContext componentContxt = (ComponentContext) request.getAttribute("com.day.cq.wcm.componentcontext");
ContentPolicy policy = policyManager.getPolicy(componentContxt);

Hope it works!

AG

Avatar

Level 1

Hi @Anudeep_Garnepudi
I am facing similar issue in my below servlet code, trying to fetch the components in the accordion component dialog's dropdown field through a component policy (under path-/conf/project/settings/wcm/policies/project/components/content/accordion/policy_869306689481091), at line 23 the currentResouce is null. Could you help me on this ?


@SlingServlet(paths = "/bin/project/authoring/accordionComponents",
description = "This servlet will return the components configured in the component policy",
methods = "GET",
metatype = false)
public class AccordionPolicyServlet extends SlingAllMethodsServlet {
private static final long serialVersionUID = -4248132624511134604L;
private static final Logger LOG = LoggerFactory.getLogger(AccordionPolicyServlet.class);

/* (non-Javadoc)
* @see org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
*/
@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
throws ServletException, IOException {
LOG.info("Inside AccordionPolicyServlet");
final String pagePath = request.getRequestURI();
String contentPath = StringUtils.substringAfter(pagePath, "_cq_dialog.html");
Resource currentResource = request.getResourceResolver().getResource(contentPath);
String resourceType = StringUtils.substringAfterLast(currentResource.getResourceType(), "/");
String accordNode = StringUtils.substringAfterLast(contentPath, "/");
if (accordNode.contains(resourceType)) {
contentPath = contentPath.replace(accordNode, resourceType);
currentResource = request.getResourceResolver().getResource(contentPath);
}
final ContentPolicyManager policyManager = request.getResourceResolver().adaptTo(ContentPolicyManager.class);
final List<Resource> optionResourceList = new ArrayList<Resource>();
ValueMap vm = null;
if (policyManager != null) {
final ContentPolicy contentPolicy = policyManager.getPolicy(currentResource);
if (contentPolicy != null) {
final String[] components = (String[]) contentPolicy.getProperties().get("components");
for (String componentPath : components) {
vm = new ValueMapDecorator(new HashMap<String, Object>());
final Resource componentRes = request.getResourceResolver().getResource(componentPath);
vm.put("text", componentRes.getValueMap().get("jcr:title"));
vm.put("value", componentPath);
optionResourceList.add(new ValueMapResource(request.getResourceResolver(),
new ResourceMetadata(), "nt:unstructured", vm));
}
}
}
final DataSource ds = new SimpleDataSource(optionResourceList.iterator());
request.setAttribute(DataSource.class.getName(), ds);
}
}

Avatar

Level 7

If you are trying to access policy of a component.

 

Do below:

 

1) In scenario I had, servlet is called from datasource attribute in dialog xml dropdown.

 

and in Servlet :

 

Resource contentResource = request.getResourceResolver().getResource((String) request.getAttribute(Value.CONTENTPATH_ATTRIBUTE));

 

ContrentPolicyManager policymanager = resolver.adaptTo(ContentPolicyManager.class);

 

ContentPolicy policy = policyManager.getPolicy(contentResource);

 

policy node will have policy details selected for that specific component at template level.

 

you can also try manjunath, anudeep answers above as well

 

Avatar

Community Advisor

Can you share what is "pagePath" value and "contentPath" values. Which are above

Resource currentResource = request.getResourceResolver().getResource(contentPath);

Avatar

Level 1

pagePath - /mnt/override/apps/project/components/content/accordion/_cq_dialog.html/content/project/sg/en/home/services/advisory/risk-consulting/cyber-security-services/managed-services/jcr:content/root/responsivegrid_718204764/accordion_1404705990_1409157200

contentPath - /content/project/sg/en/home/services/advisory/risk-consulting/cyber-security-services/managed-services/jcr:content/root/responsivegrid_718204764/accordion_1404705990_1409157200
resourceType - accordion
accordNode - accordion_1404705990_1409157200

Avatar

Community Advisor

First check if the resource "/content/project/sg/en/home/services/advisory/risk-consulting/cyber-security-services/managed-services/jcr:content/root/responsivegrid_718204764/accordion_1404705990_1409157200" exist or not. Will get null if resource is not available.

 

Suggestion here: Seems your servlet is specific to Accordion component.

Instead of path use resource type with selector and extension to bind servlet and use component content of the component to hit the servlet.

Ex: /content/project/sg/en/home/services/advisory/risk-consulting/cyber-security-services/managed-services/jcr:content/root/responsivegrid_718204764/accordion_1404705990_1409157200.<selector>.<extension>
This is best way to implement and easy to get component resource.