Expand my Community achievements bar.

July 31st AEM Gems Webinar: Elevate your AEM development to master the integration of private GitHub repositories within AEM Cloud Manager.
SOLVED

Replicator is null

Avatar

Level 2

Hi 

I am trying to create a servlet in AEM to unplish some pages. The servlet keeps throwing the nullpointer at:

replicator.replicate(session, ReplicationActionType.DEACTIVE, path); 

 

I found the root cause is the replictor is null, here's how I set it:

@reference
Replicator replicator;


I tried to do maven install and restarted the server multiple times but still not working, please advise.

 

Thank you

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

can you change Reference also to OSGi instead of Apache

 

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

View solution in original post

6 Replies

Avatar

Community Advisor

can you paste complete service class code here:

 

== example ==

import com.day.cq.replication.Replicator;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationException;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
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 javax.jcr.Session;

@component(service = MyPageDeactivationService.class)
public class MyPageDeactivationService {

@reference
private Replicator replicator;

@reference
private ResourceResolverFactory resolverFactory;

public void deactivatePage(String path) {
try {
ResourceResolver resolver = resolverFactory.getServiceResourceResolver(null);
PageManager pageManager = resolver.adaptTo(PageManager.class);
Page page = pageManager.getPage(path);

if (page != null) {
Session session = resolver.adaptTo(Session.class);
replicator.replicate(session, ReplicationActionType.DEACTIVATE, path);
}
} catch (Exception e) {
// handle exception
}
}
}

 

 

 

Avatar

Level 2

Sure, Here's the code

import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.query.RowIterator;
import javax.servlet.Servlet;

import org.osgi.service.component.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
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.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;

import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.Replicator;


/**
*this class is used to unpublish page 
*/
@Component(service = Servlet.class,
property = {
"sling.servlet.methods=" + "GET",
"sling.servlet.paths =" + "/bin/test/UnpublishPage"})
public class UnpublishPageService extends SlingAllMethodsServlet {
	
	@Reference
	Replicator replicator;
	
	private static final long serialVersionUID = -6581930898331858088L;

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    
    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
		try {
			  String queryString = "SELECT [jcr:path] FROM [cq:Page] AS s WHERE ISDESCENDANTNODE([/content/test])";


	            ResourceResolver resourceResolver = request.getResourceResolver();
	            
	            Session session = resourceResolver.adaptTo(Session.class);

	            QueryManager queryManager = session.getWorkspace().getQueryManager();

	            Query query = queryManager.createQuery(queryString, Query.JCR_SQL2);

	            QueryResult queryResult = query.execute();
	            	            
	            RowIterator rowIterator = queryResult.getRows();	           

	            while(rowIterator.hasNext()) {
	            	
	            	String path = rowIterator.nextRow().getPath();
	            	
	                Resource jcrContent = resourceResolver.getResource(path + "/jcr:content");
	                
	                Boolean autoUnpublishAtExpiry= false;	              
	                
	                ValueMap properties = jcrContent.getValueMap();
	                
	                autoUnpublishAtExpiry = properties.get("autoUnpublishAtExpiry", Boolean.class);
	                
	                Date expiryDate = properties.get("expiry", Date.class);
	                
	                Date currentDate = new Date();
	                
	            	if(autoUnpublishAtExpiry != null && autoUnpublishAtExpiry) {
	            		if(expiryDate !=null && currentDate.after(expiryDate)) {
		            		replicator.replicate(session, ReplicationActionType.DEACTIVATE, path); 
	            		}
	            	}
	            }
	            
	            session.save();
	            response.getWriter().write("Expired Page unpublished successfully");
			
		}catch(Exception e){
            log.error(e.getMessage(), e);
		}
	}
	

}

Avatar

Correct answer by
Community Advisor

can you change Reference also to OSGi instead of Apache

 

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

Avatar

Community Advisor

Hi @HanL 
Please try this

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
    try {
        String queryString = "SELECT [jcr:path] FROM [cq:Page] AS s WHERE ISDESCENDANTNODE([/content/test])";

        ResourceResolver resourceResolver = request.getResourceResolver();
        Session session = resourceResolver.adaptTo(Session.class);
        QueryManager queryManager = session.getWorkspace().getQueryManager();
        Query query = queryManager.createQuery(queryString, Query.JCR_SQL2);
        QueryResult queryResult = query.execute();
        RowIterator rowIterator = queryResult.getRows();

        while (rowIterator.hasNext()) {
            String path = rowIterator.nextRow().getPath();
            Resource jcrContent = resourceResolver.getResource(path + "/jcr:content");
            if (jcrContent != null) {
                ValueMap properties = jcrContent.getValueMap();
                Boolean autoUnpublishAtExpiry = properties.get("autoUnpublishAtExpiry", Boolean.class);
                Date expiryDate = properties.get("expiry", Date.class);
                Date currentDate = new Date();

                if (autoUnpublishAtExpiry != null && autoUnpublishAtExpiry && expiryDate != null && currentDate.after(expiryDate)) {
                    replicator.replicate(session, ReplicationActionType.DEACTIVATE, path);
                }
            }
        }

        session.save();
        response.getWriter().write("Expired Page unpublished successfully");

    } catch (Exception e) {
        log.error("Error occurred while unpublishing pages: {}", e.getMessage(), e);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write("Error occurred while unpublishing pages: " + e.getMessage());
    }
}


Avatar

Community Advisor

Check your bundle is up and running and also validate this service 

Avatar

Community Advisor

Please check if your service is up and running. Otherwise I don't see any issue with the code snippet you shared.

 

Sharing working example which is also using osgi annotation :

import org.apache.sling.api.SlingHttpServletRequest; 
import org.apache.sling.api.SlingHttpServletResponse;
 import org.apache.sling.api.servlets.SlingAllMethodsServlet;
 import org.osgi.service.component.annotations.Component;
 import org.osgi.service.component.annotations.Reference; 
 import com.day.cq.replication.ReplicationActionType; 
 import com.day.cq.replication.Replicator; 
 @component(service = SlingAllMethodsServlet.class, property = { "sling.servlet.methods=POST", "sling.servlet.paths=/bin/publishPage" })
 public class PublishPageServlet extends SlingAllMethodsServlet
 { 
 @reference
 private Replicator replicator;
 @Override
 protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws Exception
 { String path = request.getParameter("path"); // Get the path of the page to publish 
 if (path != null) 
 { 
replicator.replicate(request.getResourceResolver().adaptTo(javax.jcr.Session.class), ReplicationActionType.ACTIVATE, path);
 response.getWriter().write("Page published successfully"); 
 } else { 
 response.setStatus(400); 
 response.getWriter().write("Missing 'path' parameter"); } } }