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:
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:
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 System.out stream is intercepted and returned by the 'execute()' method.
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.
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:
- file-based JSP or ASCX DCPs;
- database-based REL DCPs;
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;
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);
publicationId);
ComponentPresentation
componentPresentation = factory.getComponentPresentation(
componentUri, componentTemplateUri);
componentUri, componentTemplateUri);
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