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...

I Have Gone Dark

Maybe it's the Holidays, but my mood has gone pretty dark. That is, regarding the look and feel of my computer and Tridion CME, of course. What I did was to dim the lights on the operating system, so I installed Placebo themes for Windows 7 . I went for the Ashtray look -- great name :) My VM looks now like this: But, once you change the theme on Windows, you should 'match' the theme of your applications. Some skin easily, some not. The Office suite has an in-built scheme, which can be set to Black , but it doesn't actually dim the ribbon tool bars -- it looks quite weird. Yahoo Messenger is skinnable, but you can't change the big white panels where you actually 'chat'. Skype is not skinnable at all. For Chrome, there are plenty of grey themes. Now i'm using Pro Grey . But then I got into changing the theme of websites. While very few offer skinnable interfaces (as GMail does), I had to find a way to darken the websites... Enter Stylish -- a pl...

REL Standard Tag Library

The RSTL is a library of REL tags providing standard functionality such as iterating collections, conditionals, imports, assignments, XML XSLT transformations, formatting dates, etc. RSTL distributable is available on my Google Code page under  REL Standard Tag Library . Always use the latest JAR . This post describes each RSTL tag in the library explaining its functionality, attributes and providing examples. For understanding the way expressions are evaluated, please read my post about the  Expression Language used by REL Standard Tag Library . <c:choose> / <c:when> / <c:otherwise> Syntax:     <c:choose>         <c:when test="expr1">             Do something         </c:when>         <c:when test="expr2">             Do something else         </c:when...