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

The JSP

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="http://www.mitza.net/dynamic-jsp-dcp/tag"%>
<html>
<head>
    <title>Dynamic JSP DCP Example</title>
</head>
<body>
    <t:componentPresentation componentUri="tcm:1-852" componentTemplateUri="tcm:1-851-32"/>
</body>
</html>

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;

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

            JspContext context = getJspContext();
            JspWriter out = context.getOut();
            out.write(result);
        } 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(
                publicationId);
        ComponentPresentation componentPresentation = factory.getComponentPresentation(
                componentUricomponentTemplateUri);

        return componentPresentation.getContent();
    }

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

        return result;
    }
}

JavaHandler

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 java.io.ByteArrayOutputStream;\r\n" +
        "import java.io.PrintStream;\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);
        compile(javaObject);
    }

    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 (!task.call()) { // compile error
            throw new RuntimeException("Compilation error");
        }
    }
}

The JSP Response

The generated HTML source:

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

</body>
</html>

Notes

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);


Comments

Popular posts from this blog

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: https://dba.stackexchange.com/questions/145982/sp-updatestats-vs-update-statistics I stumbled upon the following post from 2008 (!!!), https://social.msdn.microsoft.com/Forums/sqlserver/en-US/186e3db0-fe37-4c31-b017-8e7c24d19697/spupdatestats-fails-to-run-with-permission-error-under-dbopriveleged-user , 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

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

Debugging a Tridion 2011 Event System

OK, so you wrote your Tridion Event System. Now it's time to debug it. I know this is a hypothetical situtation -- your code never needs any kind of debugging ;) but indulge me... Recently, Alvin Reyes ( @nivlong ) blogged about being difficult to know how exactly to debug a Tridion Event System. More exactly, the question was " What process do I attach to for debugging even system code? ". Unfortunately, there is no simple or generic answer for it. Different events are fired by different Tridion CM modules. These modules run as different programs (or services) or run inside other programs (e.g. IIS). This means that you will need to monitor (or debug) different processes, based on which events your code handles. So the usual suspects are: dllhost.exe (or dllhost3g.exe ) - running as the MTSUser is the SDL Tridion Content Manager COM+ application and it fires events on generic TOM objects (e.g. events based on Tridion.ContentManager.Extensibility.Events.CrudEven