Skip to main content

Executing a JSP DCP Stored in the Database

We recently had an internal SDL discussion about what kind of Dynamic Component Presentations can be executed and how. The bottom line was, you can use the ComponentPresentationAssembler to trigger execution on:
  • file-based JSP or ASCX DCPs;
  • database-based REL DCPs;
But what about the other DCPs -- for example JSP published to the DB? You can't execute a string of characters representing a Java class. We always had this 'technology' limitation: a DCP containing code cannot be executed if published to the Database. You can only execute a DCP that is a file on the file-system.

This triggered me to mess a bit with dynamic code execution. I have done this recently in my work on the Java Mediator for SDL Tridion Templating. That post describes how to load a class dynamically and execute it.

The approach for JSP DCPs is no different:
  • Retrieve the DCP content, using ComponentPresentationFactory;
  • Compile the content (in my little example, the DCP content actually represents a Java code fragment) into a .class;
  • Execute the .class;
  • Capture the output and display it;
For simplicity sake, I created a simple Java custom tag that performs the steps above and writes the 'output from the execution' to the JSPWriter (i.e. outputs it into the JSP).

The Dynamic Component Presentation

I created a simple Dynamic Component Template that just outputs a multi-line non-formatted text field. The CT's Output Format is JSP Scripting. I published this to the Content Delivery Database.
The idea is to execute the code in the DCP, capture what is written to the System.out stream, and display it as being the 'content' of the DCP.

The Content Delivery


I implemented a small JSP that calls a custom ComponentPresentation tag based on a Component URI and a Component Template URI.

<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="t" uri=""%>
    <title>Dynamic JSP DCP Example</title>
    <t:componentPresentation componentUri="tcm:1-852" componentTemplateUri="tcm:1-851-32"/>

Simple JSP Custom Tag

The tag logic is implemented in the class below. It reads the original CP content (from the DB), then compiles it to a .class and executes it.

public class ComponentPresentationTag extends SimpleTagSupport {

    private String componentUri;
    private String componentTemplateUri;
    private int publicationId;

    public void doTag() throws JspException {
        try {
            String content = getComponentPresentationContent();
            String result = executeContent(content);

            JspContext context = getJspContext();
            JspWriter out = context.getOut();
        } catch (Exception e) {
            throw new JspException(e);

    public String getComponentUri() {
        return componentUri;

    public void setComponentUri(String componentUri) throws ParseException {
        this.componentUri = componentUri;
        publicationId = new TCMURI(componentUri).getPublicationId();

    public String getComponentTemplateUri() {
        return componentTemplateUri;

    public void setComponentTemplateUri(String componentTemplateUri) {
        this.componentTemplateUri = componentTemplateUri;

    private String getComponentPresentationContent() throws ParseException {
        ComponentPresentationFactory factory = new ComponentPresentationFactory(
        ComponentPresentation componentPresentation = factory.getComponentPresentation(

        return componentPresentation.getContent();

    private String executeContent(String content) throws Exception {
        JavaHandler handler = new JavaHandler(content);
        String result = handler.execute();

        return result;


The logic follows the Java Fragment approach from the above-mentioned Java Mediator. The original (raw) DCP content is injected into a Java source code skeleton (inside the 'execute' method), then the entire class is compiled.

The System.out stream is intercepted and returned by the 'execute()' method.

public class JavaHandler {

    private final String className = "MyClass";
    private final String content;
    private final String sourceSkeleton =
        "import;\r\n" +
        "import;\r\n" +
        "public class %s {\r\n" +
        "    public String execute() {\r\n" +
        "        ByteArrayOutputStream output = new ByteArrayOutputStream();\r\n" +
        "        System.setOut(new PrintStream(output));\r\n" +
        "        %s\r\n" +
        "        return output.toString();\r\n" +
        "    }\r\n" +
    private String classesDir = "C:\\Temp";

    public JavaHandler(String content) {
        this.content = content;

    public void compile() {
        SourceStringCompiler compiler = new SourceStringCompiler(classesDir);
        String source = String.format(sourceSkeleton, className, content);
        compiler.compile(className, source);

    public String execute() throws Exception {
        File classesDirFile = new File(classesDir);
        ClassLoader parentLoader = JavaHandler.class.getClassLoader();
        URLClassLoader loader = new URLClassLoader(new URL[] { classesDirFile.toURI().toURL() }, parentLoader);

        Class<?> clazz = loader.loadClass(className);
        Object instance = clazz.newInstance();

        Method executeMethod = clazz.getMethod("execute");
        return (String)executeMethod.invoke(instance);

The code above is obviously a quick and dirty proof-of-concept. It uses hard-coded paths (C:\temp) to store the compiled .class file; it does not use any type of caching -- the class is recompiled and then loaded using reflection for every single request.

Helper Class JavaObjectFromString

This class loads a "string://" URI into a JavaFileObject used for compilation of an in-memory representation of a Java source code class.

public class JavaObjectFromString extends SimpleJavaFileObject {

    private String sourceCode = null;

    public JavaObjectFromString(String className, String sourceCode) {
        super(URI.create("string:///" + className.replaceAll("\\.", "/") + Kind.SOURCE.extension), Kind.SOURCE);
        this.sourceCode = sourceCode;

    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
        return sourceCode;

Helper Class SourceStringCompiler

This class triggers the actual compilation of a String object representing the Java class source.

public class SourceStringCompiler {

    private String classesDir;

    public SourceStringCompiler(String classesDir) {
        this.classesDir = classesDir;

    public void compile(String fullyQualifiedClassName, String javaSource) {
        JavaFileObject javaObject = new JavaObjectFromString(fullyQualifiedClassName, javaSource);

    public void compile(JavaFileObject javaObject) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        Iterable<JavaFileObject> fileObjects = Arrays.asList(javaObject);
        Iterable<String> options = Arrays.asList("-d", classesDir);
        CompilationTask task = compiler.getTask(null, null, null, options, null, fileObjects);

        if (! { // compile error
            throw new RuntimeException("Compilation error");

The JSP Response

The generated HTML source:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Dynamic JSP DCP Example</title>
    <h1>Hello, world!</h1>
<p>Now is: Tue Dec 04 13:59:56 PST 2012</p>



This code is there just to prove a point. It can be optimized a great deal.

A more realistic approach would involve having a DCP that is in fact a JSP fragment. Then the custom tag logic would retrieve the JSP from database, and execute it. In that case, it might not even be necessary to compile the JSP into a .class or execute it using reflection -- the Application Server could take care of it, once the JSP is available somewhere under the application's context path.

The tag would simply perform a dispatcher include:
    request.getRequestDispatcher("jspFromDB.jsp").include(request, response);


Popular posts from this blog

Content Delivery Monitoring in AWS with CloudWatch

This post describes a way of monitoring a Tridion 9 combined Deployer by sending the health checks into a custom metric in CloudWatch in AWS. The same approach can also be used for other Content Delivery services. Once the metric is available in CloudWatch, we can create alarms in case the service errors out or becomes unresponsive. The overall architecture is as follows: Content Delivery service sends heartbeat (or exposes HTTP endpoint) for monitoring Monitoring Agent checks heartbeat (or HTTP health check) regularly and stores health state AWS lambda function: runs regularly reads the health state from Monitoring Agent pushes custom metrics into CloudWatch I am running the Deployer ( installation docs ) and Monitoring Agent ( installation docs ) on a t2.medium EC2 instance running CentOS on which I also installed the Systems Manager Agent (SSM Agent) ( installation docs ). In my case I have a combined Deployer that I want to monitor. This consists of an Endpoint and a

Running sp_updatestats on AWS RDS database

Part of the maintenance tasks that I perform on a MSSQL Content Manager database is to run stored procedure sp_updatestats . exec sp_updatestats However, that is not supported on an AWS RDS instance. The error message below indicates that only the sa  account can perform this: Msg 15247 , Level 16 , State 1 , Procedure sp_updatestats, Line 15 [Batch Start Line 0 ] User does not have permission to perform this action. Instead there are several posts that suggest using UPDATE STATISTICS instead: I stumbled upon the following post from 2008 (!!!), , which describes a way to wrap the call to sp_updatestats and execute it under a different user: create procedure dbo.sp_updstats with execute as 'dbo' as

Event System to Create Mapped Structure Groups for Binary Publish

As a continuation of last week's Publish Binaries to Mapped Structure Group , this week's TBB is in fact the Event System part of that solution. Make sure you do check out the previous post first, which explains why and what this Event System does. To reiterate, the Event System intercepts a Multimedia Component save, take its Folder path and create a 1-to-1 mapping of Structure Groups. The original code was written, again, by my colleague Eric Huiza : [ TcmExtension ( "MyEvents" )] public class EventsManager  : TcmExtension {     private Configuration configuration;     private readonly Regex SAFE_DIRNAME_REGEX = new Regex ( @"[\W_]+" );     public EventsManager() {         ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap ();         fileMap.ExeConfigFilename = Path .GetDirectoryName( Assembly .GetExecutingAssembly().Location) + "\\EventSystem.config" ;         configuration = ConfigurationManager