Skip to content

Instantly share code, notes, and snippets.

@nateyolles
Created October 9, 2015 03:44
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save nateyolles/1dc9f8699fce70916764 to your computer and use it in GitHub Desktop.
Save nateyolles/1dc9f8699fce70916764 to your computer and use it in GitHub Desktop.
Get the HTML markup for a resource in AEM / CQ.
package com.nateyolles.aem;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.engine.SlingRequestProcessor;
import com.day.cq.contentsync.handler.util.RequestResponseFactory;
import com.day.cq.wcm.api.WCMMode;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@SlingServlet(paths={"/bin/foo"})
public class AemResourceResolutionServlet extends SlingSafeMethodsServlet {
/** Service to create HTTP Servlet requests and responses */
@Reference
private RequestResponseFactory requestResponseFactory;
/** Service to process requests through Sling */
@Reference
private SlingRequestProcessor requestProcessor;
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
/* The resource path to resolve. Use any selectors or extension. */
String requestPath = "/content/myapp/us/en/index/jcr:content/myparsys/mycomponent_f93d.html";
/* Setup request */
HttpServletRequest req = requestResponseFactory.createRequest("GET", requestPath);
WCMMode.DISABLED.toRequest(req);
/* Setup response */
ByteArrayOutputStream out = new ByteArrayOutputStream();
HttpServletResponse resp = requestResponseFactory.createResponse(out);
/* Process request through Sling */
requestProcessor.processRequest(req, resp, request.getResourceResolver());
String html = out.toString();
}
}
@sridharjayakumar
Copy link

sridharjayakumar commented Sep 9, 2016

I'm working on something very similar for generating page preview without using ContentSync. The idea works as long as the resources are not clientlibs. See my fork.
Any ideas ?

I got around the issue by using HTMLLibraryManager to write the includes, but hoping to see a better way of doing that.

@cylinder-y
Copy link

resp.getWriter().flush(); should be used

@schandrappa660
Copy link

com.day.cq.contentsync.handler.util.RequestResponseFactory; is deprecated.
what is the alternative for this API ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment