---
title: "Velocity 中执行业务"
author: "phantom"
date: "2007-03-28T06:42:30Z"
tags: []
slug: "velocity"
draft: false
lastmod: "2007-03-28T06:42:30Z"
id: 66058
url: "https://phantom.iteye.com/blog/66058"
---

package com.jh.core.util;

import java.io.StringWriter;  
import java.util.Map;  
import java.util.Properties;

import org.apache.velocity.VelocityContext;  
import org.apache.velocity.app.Velocity;  
import org.apache.velocity.app.VelocityEngine;  
import org.apache.velocity.exception.MethodInvocationException;  
import org.apache.velocity.exception.ParseErrorException;

import com.jh.app.util.Globle;

public class VelocityUtil  
{  
   static VelocityEngine ve=null;  
   public static VelocityEngine velocity()  
   {  
   if(ve!=null){  
    return ve;  
   }  
      ve = new VelocityEngine();  
      Properties p = new Properties();  
      p.setProperty(Velocity.RUNTIME\_LOG, "velocity\_jh.log");  
      p.setProperty(Velocity.FILE\_RESOURCE\_LOADER\_PATH, Globle.VM\_PATH);  
      try  
      {  
         ve.init(p);  
      }  
      catch(Exception e)  
      {  
         e.printStackTrace();  
      }  
      return ve;  
   }

   public static void main(String args\[])  
   {  
      try  
      {  
         Velocity.init();  
      }  
      catch(Exception e)  
      {

         System.out.println("Problem initializing Velocity : " + e);  
         return;  
      }  
      VelocityContext context = new VelocityContext();  
       TTT tt= new TTT();  
       tt.setSs("vvvvvvvv");  
       tt.setQq("qqq");  
      context.put("tt", tt);  
      context.put("name", "Velocity");  
      context.put("project", "Jakarta");  
       
      StringWriter w = new StringWriter();  
//      try  
//      {  
//         velocity().mergeTemplate("example2.vm", context, w);  
//      }  
//      catch(Exception e)  
//      {  
//         System.out.println("Problem merging template : " + e);  
//      }  
      System.out.println(" template : " + w);  
     // String s = "We are using $project $name to render this.\\n #parse(\\"example2.vm\\")";  
      String s = " ${tt.qq}\_dd  ";  
       
      w = new StringWriter();  
      try  
      {  
         velocity().evaluate(context, w, "mystring", s);  
      }  
      catch(ParseErrorException pee)  
      {  
         System.out.println("ParseErrorException : " + pee);  
      }  
      catch(MethodInvocationException mee)  
      {  
         System.out.println("MethodInvocationException : " + mee);  
      }  
      catch(Exception e)  
      {  
         System.out.println("Exception : " + e);  
      }  
      System.out.println(" string : " + w);  
   }

   public static String evaluate(String vmText, Map map, String logTag)  
   {  
      // System.out.println(vmText);  
      StringWriter w = new StringWriter();  
      VelocityContext context = new VelocityContext();  
      if(map != null)  
      {  
         java.util.Iterator it = map.keySet().iterator();  
         while(it.hasNext())  
         {  
            Object obj = it.next();  
            if(obj instanceof String)  
               context.put((String) obj, map.get(obj));  
         }  
      }  
      try  
      {  
         velocity().evaluate(context, w, logTag, vmText);  
      }  
      catch(ParseErrorException pee)  
      {  
         System.out.println("ParseErrorException : " + pee);  
      }  
      catch(MethodInvocationException mee)  
      {  
         System.out.println("MethodInvocationException : " + mee);  
      }  
      catch(Exception e)  
      {  
         System.out.println("Exception : " + e);  
      }  
      return w.toString();  
   }

   public static String mergeVM(String vmFile, Map map)  
   {  
      StringWriter w = new StringWriter();  
      VelocityContext context = new VelocityContext();  
      if(map != null)  
      {  
         java.util.Iterator it = map.keySet().iterator();  
         while(it.hasNext())  
         {  
            Object obj = it.next();  
            if(obj instanceof String)  
               context.put((String) obj, map.get(obj));  
         }  
      }  
      try  
      {  
         velocity().mergeTemplate(vmFile, context, w);  
      }  
      catch(ParseErrorException pee)  
      {  
         System.out.println("ParseErrorException : " + pee);  
      }  
      catch(MethodInvocationException mee)  
      {  
         System.out.println("MethodInvocationException : " + mee);  
      }  
      catch(Exception e)  
      {  
         System.out.println("Exception : " + e);  
      }  
      return w.toString();  
   }

}

 

 

package com.jh.app.util;

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.OutputStreamWriter;  
import java.io.StringWriter;  
import java.util.HashMap;  
import java.util.Map;  
import java.util.Properties;

import org.apache.velocity.VelocityContext;  
import org.apache.velocity.app.Velocity;  
import org.apache.velocity.app.VelocityEngine;  
import org.apache.velocity.exception.ResourceNotFoundException;

 

public class VelocityUtil  
{  
 public  static String GLOBLE\_VM\_PATH = "/usr/bj\_app/ROOT";  
    private static VelocityEngine ve =null;  
    synchronized public  static VelocityEngine velocity()  
 {  
   if(ve!=null) return ve;  
   ve = new VelocityEngine();  
  Properties p = new Properties();  
  p.setProperty(Velocity.RUNTIME\_LOG, "velocity\_jh.log");  
  p.setProperty(Velocity.FILE\_RESOURCE\_LOADER\_PATH, GLOBLE\_VM\_PATH);  
  try  
  {  
   ve.init(p);  
  }  
  catch (Exception e)  
  {  
   e.printStackTrace();  
  }  
  return ve;  
 }  
    public static void main(String args\[]){  
     Map map=new HashMap();  
     map.put("Name", "王立昌");  
     map.put("util", new UtilObj());  
     System.out.println(evaluate("Hello $Name !" +  
       "" +  
       "  #set ( $dao = $util.getDao(\\"cms\\") )  \\n"+  
       "  #set ( $sql = \\"select * from News\_tab  order by NewsId desc limit 10  \\")  \\n"+  
       "  #set ( $className = \\"com.jh.app.tag.app.News\\")  \\n"+  
       "     #set ( $clazz = $util.classForName($className) )  \\n" +  
       "         $sql \\n"+  
       "     #set ( $list = $dao.getObjList( $sql,$clazz))      \\n"+  
       "     #foreach( $obj in $list )  \\n"+  
       "      $obj.Title \\n"+  
       "  #end \\n"+  
       "       \\n"  
        
       ,map,"test"));  
    }

 public static String evaluate(String vmText, Map map, String logTag)  
 {  
    
  System.err.println("########################");  
  System.err.println(vmText);  
  System.err.println("########################");  
  StringWriter w = new StringWriter();  
  VelocityContext context = new VelocityContext();  
  if (map != null)  
  {  
   java.util.Iterator it = map.keySet().iterator();  
   while (it.hasNext())  
   {  
    Object obj = it.next();  
    if (obj instanceof String)  
     context.put((String) obj, map.get(obj));  
   }  
  }

  try  
  {  
   velocity().evaluate(context, w, logTag, vmText);  
  }  
  catch (ResourceNotFoundException e)  
  {  
   //该处理是为了避免包含的文档不存在而做的处理.  
   String msg = "org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource ";  
   String str = e.toString();  
   if (str.indexOf(msg) &lt; 0)  
    return "";  
   str = str.replaceAll(msg, "");  
   str = str.replaceAll("'", "");  
   String fileName = GLOBLE\_VM\_PATH + "/" + str;  
   writeStrFile(fileName, "");  
   return evaluate(vmText, map, logTag);  
  }    
  catch (Exception e)  
  {  
   e.printStackTrace();  
  }  
  return w.toString();  
 }

 public synchronized static boolean writeStrFile(String strFileName, String strContent)  
 {  
  if (strFileName.trim().equals(""))  
   return true;

  int indx = strFileName.lastIndexOf("/");  
  if (indx &gt;= 0)  
  {  
   String strDir = strFileName.substring(0, indx);  
   File f = new File(strDir);  
   if (!f.exists())  
    f.mkdirs();  
  }  
    
  try  
  {  
   FileOutputStream fos = new FileOutputStream(strFileName);  
   try  
   {  
    OutputStreamWriter o = new OutputStreamWriter(fos, "GBK");  
    o.write(strContent);  
    fos.flush();  
    o.close();  
   }  
   finally  
   {  
     fos.close();  
   }  
  }  
  catch (Exception e)  
  {  
   e.printStackTrace();  
  }  
    
  return true;  
 }

 public static String mergeVM(String vmFile, Map map)  
 {  
  StringWriter w = new StringWriter();  
  VelocityContext context = new VelocityContext();  
  if (map != null)  
  {  
   java.util.Iterator it = map.keySet().iterator();  
   while (it.hasNext())  
   {  
    Object obj = it.next();  
    if (obj instanceof String)  
     context.put((String) obj, map.get(obj));  
   }  
  }  
  try  
  {  
   velocity().mergeTemplate(vmFile, context, w);  
  }  
  catch (Exception e)  
  {  
   e.printStackTrace();  
  }  
  return w.toString();  
 }

}