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

Scaling Policies

This post is part of a bigger topic Autoscaling Publishers in AWS . In a previous post we talked about the Auto Scaling Groups , but we didn't go into details on the Scaling Policies. This is the purpose of this blog post. As defined earlier, the Scaling Policies define the rules according to which the group size is increased or decreased. These rules are based on instance metrics (e.g. CPU), CloudWatch custom metrics, or even CloudWatch alarms and their states and values. We defined a Scaling Policy with Steps, called 'increase_group_size', which is triggered first by the CloudWatch Alarm 'Publish_Alarm' defined earlier. Also depending on the size of the monitored CloudWatch custom metric 'Waiting for Publish', the Scaling Policy with Steps can add a difference number of instances to the group. The scaling policy sets the number of instances in group to 1 if there are between 1000 and 2000 items Waiting for Publish in the queue. It also sets the

Toolkit - Dynamic Content Queries

This post if part of a series about the  File System Toolkit  - a custom content delivery API for SDL Tridion. This post presents the Dynamic Content Query capability. The requirements for the Toolkit API are that it should be able to provide CustomMeta queries, pagination, and sorting -- all on the file system, without the use third party tools (database, search engines, indexers, etc). Therefore I had to implement a simple database engine and indexer -- which is described in more detail in post Writing My Own Database Engine . The querying logic does not make use of cache. This means the query logic is executed every time. When models are requested, the models are however retrieved using the ModelFactory and those are cached. Query Class This is the main class for dynamic content queries. It is the entry point into the execution logic of a query. The class takes as parameter a Criterion (presented below) which triggers the execution of query in all sub-criteria of a Criterio