Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yan-kisen/3e3fe8ee3d350b1312fccd5f960d0ff8 to your computer and use it in GitHub Desktop.
Save yan-kisen/3e3fe8ee3d350b1312fccd5f960d0ff8 to your computer and use it in GitHub Desktop.
Get the HTML markup for a resource in Apache Sling.
package com.nateyolles.sling;
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 javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@SlingServlet(paths={"/bin/foo"})
public class SlingResourceResolutionServlet extends SlingSafeMethodsServlet {
/** 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";
/*
* Create a fake request and fake response. The response adds a method to make the HTML accessible.
* You need the following three files from Apache Sling:
*
* https://github.com/apache/sling/blob/trunk/testing/junit/scriptable/src/main/java/org/apache/sling/junit/scriptable/HttpRequest.java
* https://github.com/apache/sling/blob/trunk/testing/junit/scriptable/src/main/java/org/apache/sling/junit/scriptable/HttpResponse.java
* https://github.com/apache/sling/blob/trunk/testing/junit/scriptable/src/main/java/org/apache/sling/junit/scriptable/TestServletOutputStream.java
*/
final HttpRequest req = new HttpRequest(requestPath);
final HttpResponse resp = new HttpResponse();
/* Process request through Sling */
requestProcessor.processRequest(req, resp, request.getResourceResolver());
String html = resp.getContent();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment