You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@velocity.apache.org by jv...@locus.apache.org on 2000/11/03 15:42:04 UTC

cvs commit: jakarta-velocity/src/java/org/apache/velocity/texen/util BaseUtil.java FileUtil.java StringUtil.java

jvanzyl     00/11/03 06:42:03

  Added:       src/java/org/apache/velocity/texen Generator.java
               src/java/org/apache/velocity/texen/ant TexenTask.java
               src/java/org/apache/velocity/texen/util BaseUtil.java
                        FileUtil.java StringUtil.java
  Log:
  - added modified version of Leon's submission of texen, a general
    source generating tool for Velocity. Again this may be reorganized
    later and moved out of Vel proper but it can stay here for now
    until we decide how to organize the sources before release.
  
  Revision  Changes    Path
  1.1                  jakarta-velocity/src/java/org/apache/velocity/texen/Generator.java
  
  Index: Generator.java
  ===================================================================
  package org.apache.velocity.texen;
  
  // JDK Classes
  import java.io.*;
  import java.util.*;
  
  // Velocity Classes
  import org.apache.velocity.Context;
  import org.apache.velocity.Template;
  import org.apache.velocity.runtime.Runtime;
  
  // Local Classes
  import org.apache.velocity.texen.util.BaseUtil;
  
  /**
   * A text/code generator class
   *
   * @author <a href="mailto:leon@opticode.co.za">Leon Messerschmidt</a>
   * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
   * @version $Id: Generator.java,v 1.1 2000/11/03 14:42:00 jvanzyl Exp $ 
   */
  public class Generator
  {
      public static final String PATH_INPUT = "path.input";
      public static final String PATH_OUTPUT = "path.output";
      public static final String CONTEXT_STRINGS = "context.objects.strings";
      public static final String CONTEXT_FILES = "context.objects.files";
      
      Properties props = new Properties();
  
      //Generator instance = new Generator();
  
      /**
       * Create a new generator object with default properties
       */
      public Generator ()
      {
          setDefaultProps();
      }
      
      
      /**
       * Create a new generator object with properties loaded from
       * a file.  If the file does not exist or any other exception
       * occurs during the reading operation the default properties
       * are used.
       */
      public Generator (String propFile)
      {
          try
          {
              FileInputStream fi = new FileInputStream (propFile);
              BufferedInputStream bi = new BufferedInputStream (fi);
              try
              {
                  props.load (bi);
              }
              finally
              {
                  bi.close();
              }
          }
          catch (Exception e)
          {
              // If something goes wrong we use default properties
              setDefaultProps();
          }
      }
      
      /**
       * Create a new Generator object with a given property
       * set.  The property set will be duplicated.
       */
      public Generator (Properties props)
      {
          this.props = (Properties)props.clone();
      }
      
      
      /**
       * Set default properties
       */
      protected void setDefaultProps()
      {
          props.setProperty (PATH_INPUT,".");
          props.setProperty (PATH_OUTPUT,"output/");
          props.setProperty (CONTEXT_STRINGS,"org.apache.velocity.texen.util.StringUtil");
          props.setProperty (CONTEXT_FILES,"org.apache.velocity.texen.util.FileUtil");
      }
          
      /**
       * Get a property from the propery set of this generator.
       */        
      public String getProperty (String name)
      {
          return props.getProperty (name,"");
      }
  
      /**
       * Get a property from the propery set of this generator.
       */        
      public void setProperty (String key, String value)
      {
          props.put(key,value);
      }
  
      /**
       * Parse an input file and return the result as a String
       * object.
       */ 
      
      /*
      public String parse (String input) throws Exception
      {
          return this.parse (input,null);
      }
      */
       
      /**
       * Parse an input and write the output to an output file.  If the
       * output file parameter is null or an empty string the result is
       * returned as a string object.  Otherwise an empty string is returned.
       */ 
      public String parse (String input, String output) throws Exception
      {
          return this.parse (input,output,null,null);
      }
      
      /**
       * Parse an input and write the output to an output file.  If the
       * output file parameter is null or an empty string the result is
       * returned as a string object.  Otherwise an empty string is returned.
       * You can add one object (obj) to the context with the name objName.
       */ 
      public String parse (String input, String output, String objName, Object obj) 
          throws Exception
      {
          Hashtable h = new Hashtable();
          if (objName != null && obj != null)
          {
              h.put (objName,obj);
          }
          
          return this.parse (input,output,h);
      }
      
      /**
       * Parse an input and write the output to an output file.  If the
       * output file parameter is null or an empty string the result is
       * returned as a string object.  Otherwise an empty string is returned.
       * You can add objects to the context with the objs Hashtable.
       */ 
      public String parse (String input, String output, Hashtable objs) 
          throws Exception
      {
          try
          {
          Context context = getContext (objs);
          
          Template template = Runtime.getTemplate(input);
          
          if (output == null || output.equals(""))
          {
              StringWriter sw = new StringWriter();
              template.merge (context,sw);
              return sw.toString();
          }
          else
          {
              FileWriter fw = new FileWriter (props.getProperty (PATH_OUTPUT)+
                                              File.separator +
                                              output);
              template.merge (context,fw);
              fw.close();
              
              return "";
          }
          }
          catch (Exception e)
          {
              e.printStackTrace();
              return null;
          }
          
      }
  
      public String parse (String controlTemplate, Context controlContext)
          throws Exception
      {
          fillContextDefaults(controlContext);
          fillContextProperties(controlContext);
          
          Template template = Runtime.getTemplate(controlTemplate);
          StringWriter sw = new StringWriter();
          template.merge (controlContext,sw);
          
          return sw.toString();
      }
  
  
      /**
       * Create a new context and fill it with the elements of the
       * objs Hashtable.  Default objects and objects that comes from
       * the properties of this Generator object is also added.
       */ 
      protected Context getContext (Hashtable objs)
      {
          Context context = new Context();
          
          fillContextHash (context,objs);
          fillContextDefaults (context);
          fillContextProperties (context);
          
          return context;
      }
  
      /** 
       * Add all the contents of a Hashtable to the context
       */
      protected void fillContextHash (Context context, Hashtable objs)
      {
          Enumeration enum = objs.keys();
          while (enum.hasMoreElements())
          {
              String key = enum.nextElement().toString();
              context.put (key, objs.get(key));
          }
      }
      
  
      /**
       * Add properties that will aways be in the context by default
       */
      protected void fillContextDefaults (Context context)
      {
          Generator gen = new Generator (props);
          context.put ("generator",gen);
      }
      
      /**
       * Add objects to the context from the current properties
       */
      protected void fillContextProperties (Context context)
      {
          Enumeration enum = props.propertyNames();
          
          while (enum.hasMoreElements())
          {
              String nm = (String)enum.nextElement();
              if (nm.startsWith ("context.objects."))
              {
                  
                  String contextObj = props.getProperty (nm);
                  int colon = nm.lastIndexOf ('.');
                  String contextName = nm.substring (colon+1);
                  
                  try
                  {
                      Class cls = Class.forName (contextObj);
                      BaseUtil b = (BaseUtil)cls.newInstance();
                      b.init();
                      context.put (contextName,b);
                  }
                  catch (Exception e)
                  {
                      e.printStackTrace();
                      //TO DO: Log Something Here
                  }
              }
              
          }
          
      }
      
      /**
       * Just 4 Testing
       */
      
      /*
      public static void main (String[] args) throws Exception
      {
          Runtime.init("velocity.properties");
          //Runtime.init();
          
          Generator gen = new Generator();
          System.out.println (gen.parse (args[0]));
      }
      */
           
  }
  
  
  
  1.1                  jakarta-velocity/src/java/org/apache/velocity/texen/ant/TexenTask.java
  
  Index: TexenTask.java
  ===================================================================
  package org.apache.velocity.texen.ant;
  
  /*
   * Copyright (c) 1997-2000 The Java Apache Project.  All rights 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.
   *
   * 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. All advertising materials mentioning features or use of this
   *    software must display the following acknowledgment:
   *    "This product includes software developed by the Java Apache
   *    Project for use in the Apache JServ servlet engine project
   *    <http://java.apache.org/>."
   *
   * 4. The names "Apache JServ", "Apache JServ Servlet Engine", "Turbine",
   *    "Apache Turbine", "Turbine Project", "Apache Turbine Project" and
   *    "Java Apache Project" must not be used to endorse or promote products
   *    derived from this software without prior written permission.
   *
   * 5. Products derived from this software may not be called "Apache JServ"
   *    nor may "Apache" nor "Apache JServ" appear in their names without
   *    prior written permission of the Java Apache Project.
   *
   * 6. Redistributions of any form whatsoever must retain the following
   *    acknowledgment:
   *    "This product includes software developed by the Java Apache
   *    Project for use in the Apache JServ servlet engine project
   *    <http://java.apache.org/>."
   *
   * THIS SOFTWARE IS PROVIDED BY THE JAVA APACHE PROJECT "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 JAVA APACHE PROJECT 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.
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Java Apache Group. For more information
   * on the Java Apache Project and the Apache JServ Servlet Engine project,
   * please see <http://java.apache.org/>.
   *
   */
  
  import java.util.Map;
  import java.util.Hashtable;
  
  // Ant Stuff
  import org.apache.tools.ant.BuildException;
  import org.apache.tools.ant.Task;
  
  // Velocity Stuff
  import org.apache.velocity.Context;
  import org.apache.velocity.runtime.Runtime;
  import org.apache.velocity.texen.Generator;
  
  /**
   * An ant task for generating output by using Velocity
   *
   * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
   * @version $Id: TexenTask.java,v 1.1 2000/11/03 14:42:01 jvanzyl Exp $
   */
  
  public abstract class TexenTask extends Task
  {
      protected String controlTemplate;
      protected String templatePath;
      protected String outputDirectory;
  
      protected Hashtable options = new Hashtable();
  
      /**
       * Set the output directory.  This directory must exist.
       */
      public void setControlTemplate (String controlTemplate)
      {
          this.controlTemplate = controlTemplate;
      }
  
      public String getControlTemplate()
      {
          return controlTemplate;
      }
  
      public void setTemplatePath(String templatePath)
      {
          this.templatePath = templatePath;
      }
      
      public String getTemplatePath()
      {
          return templatePath;
      }        
  
      public void setOutputDirectory(String outputDirectory)
      {
          this.outputDirectory = outputDirectory;
      }
      
      public String getOutputDirectory()
      {
          return outputDirectory;
      }        
  
      public void setOption(String option)
      {
          String optionName = option.substring(0, option.indexOf(":") - 1);
          String optionValue = option.substring(option.indexOf(":"));
          
          options.put(optionName, optionValue);
      }
  
      public String getOption(String optionName)
      {
          return (String) options.get(optionName);
      }
  
      public abstract Context initControlContext();
      
      /**
       * Execute the input script with WM
       */
      public void execute () throws BuildException
      {
          // Make sure the template path is set.
          if (templatePath == null)
              throw new BuildException("The template path needs to be " +
                                       "defined! Texen can't run.");
  
          if (controlTemplate == null)
              throw new BuildException("The control template needs to be " +
                                       "defined! Texen can't run.");
  
          try
          {
              // Setup the Velocity Runtime.
              Runtime.setDefaultProperties();
              Runtime.setProperty(Runtime.TEMPLATE_PATH, templatePath);
              Runtime.init();
          
              // Create the text generator.
              Generator generator = new Generator();
              generator.setProperty(Generator.PATH_INPUT,templatePath);
              
              System.out.println(generator.parse(controlTemplate, initControlContext()));
          }
          catch (Exception e)
          {
              e.printStackTrace();
          }
      }
  }
  
  
  
  1.1                  jakarta-velocity/src/java/org/apache/velocity/texen/util/BaseUtil.java
  
  Index: BaseUtil.java
  ===================================================================
  package org.apache.velocity.texen.util;
  
  /*
   *
   * @author <a href="mailto:leon@opticode.co.za">Leon Messerschmidt</a>
   */
   
  public class BaseUtil
  {
      public void init()
      {
      }
      
  }
  
  
  
  1.1                  jakarta-velocity/src/java/org/apache/velocity/texen/util/FileUtil.java
  
  Index: FileUtil.java
  ===================================================================
  package org.apache.velocity.texen.util;
  
  
  import java.io.*;
  import java.util.*;
  
  /**
   * A general file utility for use in the context
   *
   * @author <a href="mailto:leon@opticode.co.za>Leon Messerschmidt</a>
   */
  
  public class FileUtil extends BaseUtil
  {
      /**
       * Creates the directory s (and any parent directories needed)
       */
      static public String mkdir (String s)
      {
          try
          {
              if ((new File(s)).mkdirs())
                  return "Created dir: "+s;
              else
                  return "Failed to create dir or dir already exists: "+s;
          }
          catch (Exception e)
          {
              return e.toString();
          }
  
      }
  
  }
  
  
  
  1.1                  jakarta-velocity/src/java/org/apache/velocity/texen/util/StringUtil.java
  
  Index: StringUtil.java
  ===================================================================
  package org.apache.velocity.texen.util;
  
  
  // JDK Classes
  import java.io.*;
  import java.util.*;
  
  /**
   * A string utility class for the texen text/code generator
   * Usually this class is only used from a Velcity context.
   *
   * @author <a href="mailto:leon@opticode.co.za">Leon Messerschmidt</a>
   */
  public class StringUtil extends BaseUtil
  {
      
      /**
       * Concatenates a list of objects as a String
       */
      public String concat (Object[] list)
      {
          StringBuffer sb = new StringBuffer();
          for (int i=0; i<list.length; i++)
          {
              sb.append (list[i].toString());
          }
          return sb.toString();
      }
      
      /**
       * Return a package name as a relative path name
       */
      static public String getPackageAsPath(String pckge)
      {
          return pckge.replace( '.', File.separator.charAt(0) ) + File.separator;
      }
  
    /**
     * Remove Underscores from a string and replaces first
     * Letters with Capitals.  foo_bar becomes FooBar
     */
      static public String removeUnderScores (String data)
      {
          String temp = null;
          StringBuffer out = new StringBuffer();
          temp = data;
  
          StringTokenizer st = new StringTokenizer(temp, "_");
          while (st.hasMoreTokens())
          {
              String element = (String) st.nextElement();
              out.append ( firstLetterCaps(element));
          }//while
          return out.toString();
      }
  
    /**
     * Makes the first letter caps and the rest lowercase
     */
      static public String firstLetterCaps ( String data )
      {
          String firstLetter = data.substring(0,1).toUpperCase();
          String restLetters = data.substring(1).toLowerCase();
          return firstLetter + restLetters;
      }
  }