Return-Path: Mailing-List: contact tomcat-dev-help@jakarta.apache.org; run by ezmlm Delivered-To: mailing list tomcat-dev@jakarta.apache.org Delivered-To: moderator for tomcat-dev@jakarta.apache.org Received: (qmail 56323 invoked from network); 27 Sep 2000 22:24:25 -0000 Received: from lukla.sun.com (192.18.98.31) by locus.apache.org with SMTP; 27 Sep 2000 22:24:25 -0000 Received: from engmail3.Eng.Sun.COM ([129.144.170.5]) by lukla.Sun.COM (8.9.3+Sun/8.9.3) with ESMTP id QAA27142 for ; Wed, 27 Sep 2000 16:24:20 -0600 (MDT) Received: from heliopolis.Eng.Sun.COM (heliopolis.Eng.Sun.COM [152.70.1.39]) by engmail3.Eng.Sun.COM (8.9.3+Sun/8.9.3/ENSMAIL,v1.7) with ESMTP id PAA21565 for ; Wed, 27 Sep 2000 15:24:18 -0700 (PDT) Received: from yared (yared [152.70.40.119]) by heliopolis.Eng.Sun.COM (8.9.1b+Sun/8.9.1) with SMTP id PAA26171 for ; Wed, 27 Sep 2000 15:24:18 -0700 (PDT) From: "Peter Yared" To: Subject: Using Tomcat/Jasper as a code generator/template language Date: Wed, 27 Sep 2000 15:27:38 -0700 Message-ID: MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_000A_01C02897.77CB5180" X-Priority: 3 (Normal) X-MSMail-Priority: Normal X-Mailer: Microsoft Outlook IMO, Build 9.0.2416 (9.0.2910.0) Importance: Normal X-MimeOLE: Produced By Microsoft MimeOLE V4.72.3612.1700 X-Spam-Rating: locus.apache.org 1.6.2 0/1000/N ------=_NextPart_000_000A_01C02897.77CB5180 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hi everyone, Enclosed is a file that enables people to use Tomcat/Jasper as a code generator. What is nice is that it invokes Tomcat/Jasper directly, so it doesn't use Apache, ports, etc., and therefore can very easily be integrated into an application. It also lets you pass session variables that can then be used by the JSP page to help generate code. Following is an example of how to use the JspTemplateCompiler. The source file is enclosed. Enjoy! Peter Yared SunLabs SunMicrosystems, Inc. peter.yared(remove me)eng.sun.com You can make a template like the following JSP: <%@ page %> <% if (packageName != null && packageName.length() > 0) { %> package <%= packageName %>; <% } %> public class <%= className %> { public <%= className %>() { } public int returnCustomNumber() { return <%= 3+3 %>; } public String returnSessionString() { return "<%= myString %>"; } } Which is then used to generate a .java file: import java.io.IOException; import java.util.Hashtable; import javax.servlet.ServletException; import org.apache.jasper.JspTemplateCompiler; public class ServletTest { public ServletTest() { try { Hashtable properties = new Hashtable(); properties.put("myString", "Yo"); org.apache.jasper.JspTemplateCompiler.debug = true; org.apache.jasper.JspTemplateCompiler.processTemplate("D:\\jsps\\My.jsp", "D:\\jsps\\MyClass.java", null, "MyClass", properties, null, null, true); } catch (IOException e) { e.printStackTrace(); } catch (ServletException e) { e.printStackTrace(); } } public static void main(String[] args) { ServletTest servletTest = new ServletTest(); } } ------=_NextPart_000_000A_01C02897.77CB5180 Content-Type: application/octet-stream; name="JspTemplateCompiler.java" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="JspTemplateCompiler.java" /* * * = =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D *=20 * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights=20 * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer.=20 * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: =20 * "This product includes software developed by the=20 * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software = itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products = derived * from this software without prior written permission. For written=20 * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * = =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * . * */=20 package org.apache.jasper; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import sun.tools.javac.*; import org.apache.jasper.*; import org.apache.tomcat.core.*; import org.apache.tomcat.loader.*; import org.apache.tomcat.session.*; import org.apache.jasper.runtime.*; /** * The JspTemplateCompiler compiles JSP pages that render Java code. = This is a useful way of * creating Java code templates to dynamically generate Java code. = JspTemplateCompiler uses * the sun.tools.javac compiler, which is available in many Java = Development Kit implementations. * * @author Peter Yared, SunLabs, peter.yared@eng.sun.com */ public class JspTemplateCompiler { /** * Debug flag that prints JSP result to System.out. */ public static boolean debug =3D false; =20 /** * Generates a Java file from a JSP template and compiles it. * * @param templatePath Path to .jsp to use to generate file * @param targetPath File path to place the generated file * @param targetPackage Package name to use in the JSP template = (passed as session parameter packageName) * @param targetClassName Class name to use in the JSP template = (passed as session parameter className) * @param properties Hashtable of session properties to be made = available to the jsp template * @param classPath Classpath to use when compiling files * @param compile Flag to specify if result of servlet should be = compiled with javac * @returns boolean Successful t/f */ public static boolean processTemplate(String templatePath, String = targetPath, String targetPackage, String targetClassName, Hashtable = properties, String servletClassPath, String templateClassPath, boolean = compile) throws IOException, ServletException { =20 // Get the path, file name, and servlet name from templatePath = variable int fileNameIndex =3D = templatePath.lastIndexOf(File.separatorChar); String path =3D null; String fileName =3D null; if (fileNameIndex =3D=3D -1) { fileName =3D templatePath; } else { fileName =3D templatePath.substring(fileNameIndex + 1); path =3D templatePath.substring(0, fileNameIndex + 1); } String servletName =3D fileName.substring(0, fileName.length() - = 4); // Remove ".jsp" from end =20 // Convert the JSP to a Servlet String[] jspcArgs =3D new String[5]; jspcArgs[0] =3D "-uriroot"; jspcArgs[1] =3D path; jspcArgs[2] =3D "-d"; jspcArgs[3] =3D path; jspcArgs[4] =3D fileName; JspC.main(jspcArgs); =20 // Compile the Servlet - need to do it ourselves since tomcat = does it for you on a HTTP request if (!compile(servletClassPath, path + File.separatorChar + = servletName + ".java")) return false; =20 // Pass the target path to the session so it can be used if (properties =3D=3D null) { properties =3D new Hashtable(); } if (targetPackage !=3D null) { properties.put("packageName", targetPackage); } properties.put("className", targetClassName); =20 // Write the result of the servlet to disk File file =3D new File(targetPath); file.delete(); // Delete it if it already exists FileWriter fw =3D new FileWriter(file); String jspResult =3D runServlet(path, servletName, = properties).toString(); if (debug) { System.out.println(jspResult); } fw.write(jspResult); fw.close(); =20 // Compile the output of the servlet if (compile) { return compile(templateClassPath, targetPath); } return true; } =20 /** * Compiles a file using the sun.tools.javac compiler. * * @param classPath The classpath to use when compiling, can be null * @param file to compile * @returns boolean Successful t/f */=20 protected static boolean compile(String classPath, String file) { String[] args =3D new String[(classPath =3D=3D null) ? 1 : 3]; args[0] =3D file; if (classPath !=3D null) { args[1] =3D "-classpath"; args[2] =3D classPath; } Main compiler =3D new Main(System.out, "JSP Template Compiler"); return compiler.compile(args); } =20 /** * Runs a servlet and returns its result as a StringBuffer * * @param docBase The location of the servlet * @param servletName The name of the servlet to run * @param properties Hashtable of session properties to be made = available to the jsp template * @param returns StringBuffer with result of the servlet */ public static StringBuffer runServlet(String docBase, String = servletName, Hashtable properties) throws IOException, = javax.servlet.ServletException { org.apache.tomcat.core.ServletWrapper servletWrapper =3D new = org.apache.tomcat.core.ServletWrapper(); =20 org.apache.tomcat.core.Context cntx =3D new = org.apache.tomcat.core.Context(); =20 org.apache.tomcat.core.ContextManager cm =3D new = org.apache.tomcat.core.ContextManager(); cntx.setContextManager(cm); =20 org.apache.tomcat.core.ServletLoader sloader =3D new = org.apache.tomcat.loader.ServletClassLoaderImpl(); sloader.addRepository(new File(docBase)); cntx.setServletLoader(sloader); =20 org.apache.tomcat.core.SessionManager sm =3D new = org.apache.tomcat.session.StandardSessionManager(); cntx.setSessionManager(sm); =20 servletWrapper.setContext(cntx); servletWrapper.setServletName(servletName); servletWrapper.setServletClass(servletName); javax.servlet.Servlet servlet =3D servletWrapper.getServlet(); =20 javax.servlet.jsp.JspFactory myFactory =3D new = org.apache.jasper.runtime.JspFactoryImpl(); JspFactory.setDefaultFactory(myFactory); org.apache.tomcat.core.RequestImpl request =3D new = RequestImpl(); org.apache.tomcat.core.ResponseImpl response =3D new = ResponseImpl(); =20 request.setContextManager(cm); request.setContext(cntx); =20 response.setRequest(request); request.setResponse(response); =20 HttpSession session =3D request.getFacade().getSession(true); if (properties !=3D null) { Enumeration e =3D properties.keys(); while (e.hasMoreElements()) { String key =3D (String) e.nextElement(); session.setAttribute(key, properties.get(key)); } } servlet.service(request.getFacade(), response.getFacade()); response.finish(); =20 return ((ResponseImpl) response).getBody(); } } ------=_NextPart_000_000A_01C02897.77CB5180--