使用Velocity將java代碼轉換成JS代碼

爲什麼要用Velocity:項目中需要將JAVA代碼生成JS代碼,但是又不想在JS中import JAVA類,而且類中有很多枚舉元素,如果手動的將枚舉元素轉換成JS對象會很耗時,所以採用Velocity模板技術讓JAVA枚舉對象自動轉換成JS文件。

準備工作:

Velocity相關架包:Velocity-1.5.jar等

熟悉Velocity相關語法

下面貼上我寫得代碼

要轉換成JS的JAVA枚舉類:

  1. /** 
  2.  * we copy the struct from taobao 
  3.  * http://dev.open.taobao.com/dev/index.php/%E9%94 
  4.  * %99%E8%AF%AF%E7%A0%81%E4%B8%80%E8%A7%88%E8%A1%A8 
  5.  *  
  6.  * @author stream 
  7.  *  
  8.  */  
  9. public enum PlatformError {  
  10.     HTTP_CONNECTION_INVALID("2","Http Connection Invalid"),  
  11.     UPLOAD_FAIL("3""Upload Fail"),  
  12.     APP_CALL_LIMITED("7""App Call Limited"),  
  13.     HTTP_ACTION_NOT_ALLOWED("9","Http Action Not Allowed"),  
  14.     SERVICE_CURRENTLY_UNAVAILABLE("10""Service Currently Unavailable"),   
  15.     INSUFFICIENT_ISV_PERMISSIONS("11""Insufficient ISV Permissions"),   
  16.     INSUFFICIENT_USER_PERMISSIONS("12""Insufficient User Permissions"),   
  17.     INSUFFICIENT_PARTNER_PERMISSIONS("13""Insufficient Partner Permissions"),   
  18.     REMOTE_SERVICE_ERROR("15""Remote service error"),   
  19.     MISSING_METHOD("21""Missing Method"),   
  20.     INVALID_METHOD("22""Invalid Method"),   
  21.     INVALID_FORMAT("23""Invalid Format"),   
  22.     MISSING_SIGNATURE("24""Missing Signature"),   
  23.     INVALID_SIGNATURE("25""Invalid Signature"),   
  24.     MISSING_SESSION("26","Missing session"),   
  25.     INVALID_SESSION("27""Invalid Session"),   
  26.     MISSING_APP_KEY("28""Missing App Key"),   
  27.     INVALID_APP_KEY("29""Invalid App Key"),   
  28.     MISSING_TIMESTAMP("30""Missing Timestamp"),   
  29.     INVALID_TIMESTAMP("31","Invalid Timestamp"),   
  30.     MISSING_VERSION("32""Missing Version"),   
  31.     INVALID_VERSION("33""Invalid Version"),   
  32.     UNSUPPORTED_VERSION("34""Unsupported Version"),   
  33.     MISSING_REQUIRED_ARGUMENTS("40""Missing required arguments"),   
  34.     INVALID_ARGUMENTS("41""Invalid arguments"),   
  35.     FORBIDDEN_REQUEST("42""Forbidden Request"),   
  36.     PARAMETER_ERROR("43","Parameter Error"),   
  37.     INVALID_ENCODING("47""Invalid encoding"),  
  38.     MISSING_TARGET("50""Missing Target"),  
  39.     MISSING_LICENSE("51""Missing License"),  
  40.     MISSING_APPPARAMS("52""Missing AppParams"),  
  41.     INVALID_LICENSE2TARGET("53""Invalid License To Target"),  
  42.     INVALID_NODE("54""Invalid Node"),  
  43.       
  44.     // above 100  
  45.     OVERTIME_SESSIONKEY("100""overtime session key "),  
  46.     INVALID_SESSIONKEY("101","invalid session key"),  
  47.     NOTMATCH_APP_KEY("108","app key is not match user"),  
  48.       
  49.     //add by stream 第三方平臺未知錯誤,產生的原因主要是匹配不到我們平臺的錯誤code  
  50.     ThirdPlatform_UNKNOW_ERROR("102","unknow error from third platform");  
  51.       
  52.     private String code;  
  53.   
  54.     private String msg;  
  55.   
  56.     private PlatformError(String code, String msg) {  
  57.         this.code = code;  
  58.         this.msg = msg;  
  59.     }  
  60.   
  61.     public String code() {  
  62.         return code;  
  63.     }  
  64.   
  65.     public String msg() {  
  66.         return msg;  
  67.     }  
  68.   
  69.     public static PlatformError getErrorByCode(String code) {  
  70.         for (PlatformError error : PlatformError.values())  
  71.             if (error.code().equals(code))  
  72.                 return error;  
  73.         return null;  
  74.     }  
  75.       
  76.     public static void main(String[] args) {  
  77.         System.out.println(PlatformError.FORBIDDEN_REQUEST.msg());  
  78.     }  
  79. }  

編寫Velocity轉換類
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.StringWriter;  
  4. import java.util.ArrayList;  
  5. import java.util.HashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8. import java.util.Properties;  
  9.   
  10. import org.apache.velocity.Template;  
  11. import org.apache.velocity.VelocityContext;  
  12. import org.apache.velocity.app.Velocity;  
  13. import org.apache.velocity.app.VelocityEngine;  
  14.   
  15. public class VelocityTest {  
  16.        
  17.     public static void main(String[] args) throws Exception {  
  18.         //創建引擎  
  19.         VelocityEngine velocityEngine = new VelocityEngine();  
  20.            
  21.         //設定輸入輸出編碼可支持中文  
  22.         Properties prop = new Properties();  
  23.         prop.setProperty(Velocity.ENCODING_DEFAULT, "utf-8");   
  24.         prop.setProperty(Velocity.INPUT_ENCODING, "utf-8");   
  25.         prop.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");   
  26.            
  27.         //可以根據屬性對象或者屬性文件進行定義,原理是一樣的.  
  28.         velocityEngine.init(prop);  
  29.            
  30.         //取得VTL定義的文件獲取模板對象  
  31.         Template template = velocityEngine.getTemplate("/src/cn/demo/util/velocity/template.vm");  
  32.            
  33.         //新創一個Velocity上下文  
  34.         VelocityContext velocityContext = new VelocityContext();  
  35.            
  36.         //放入VTL中定義的變量值  
  37.         velocityContext.put("name""ChenST");  
  38.         velocityContext.put("address""淘寶商城");  
  39.            
  40.         List<String> products = new ArrayList<String>();  
  41.         products.add("百事可樂");  
  42.         products.add("可口可樂");  
  43.         //可放入一個ArrayList集合代表數組  
  44.         velocityContext.put("products", products);  
  45.            
  46.         Map<String, String> map = new HashMap<String, String>();  
  47.         map.put("key""mapValue");  
  48.         //可放入一個Map結構的對象  
  49.         velocityContext.put("map", map);  
  50.            
  51.         //可放入一個自定義對象  
  52.   
  53.         velocityContext.put("error", PlatformError.values());  
  54.            
  55.         StringWriter stringWriter = new StringWriter();  
  56.         //根據模板定義的內容進行合併,並將結果輸出給流對象  
  57.         template.merge(velocityContext, stringWriter);  
  58.         System.out.println(stringWriter.toString());  
  59.         //生成JS文件  
  60.         new FileOutputStream(new File("E:\\demo.js")).write(stringWriter.toString()   
  61.                 .getBytes());   
  62.           
  63.     }  
  64. }  

定義模板文件/src/cn/demo/util/velocity/template.vm
  1. //velocity測試  
  2. var test = {  
  3.     name:${name},  
  4.     address:${address},  
  5.     products:  
  6.         #foreach($p in $products)  
  7.             #if($velocityCount==1)  
  8.                 ${p}  
  9.             #end  
  10.             #if($velocityCount!=1)  
  11.                 ,${p}  
  12.             #end  
  13.         #end,  
  14.     map:{  
  15.         #foreach($m in $map.entrySet())  
  16.             #if($velocityCount==1)  
  17.                 ${m.key}:${m.value}  
  18.             #end  
  19.             #if($velocityCount!=1)  
  20.                 ,${m.key}:${m.value}  
  21.             #end  
  22.               
  23.         #end  
  24.         }  
  25. }  
  26.   
  27. //錯誤定義  
  28. var platformError = {  
  29.     #foreach( $e in $error )   
  30.           #if($velocityCount==1)  
  31.             ${e}:{code:"${e.code()}",msg:"${e.msg()}"}#end #if($velocityCount!=1),${e}:{code:"${e.code()}",msg:"${e.msg()}"}  
  32.           #end  
  33.     #end   
  34. }  
運行main方法生成的demo.js爲
[javascript] view plaincopy
  1. //velocity測試  
  2. var test = {  
  3.     name:ChenST,  
  4.     address:淘寶商城,  
  5.     products:百事可樂,可口可樂,  
  6.     map:{  
  7.             key2:mapValue2  
  8.             ,key1:mapValue1  
  9.     }  
  10. }  
  11.   
  12. //錯誤定義  
  13. var platformError = {  
  14.                                 HTTP_CONNECTION_INVALID:{code:"2",msg:"Http Connection Invalid"}                    
  15.                            ,UPLOAD_FAIL:{code:"3",msg:"Upload Fail"}  
  16.                                ,APP_CALL_LIMITED:{code:"7",msg:"App Call Limited"}  
  17.                                ,HTTP_ACTION_NOT_ALLOWED:{code:"9",msg:"Http Action Not Allowed"}  
  18.                                ,SERVICE_CURRENTLY_UNAVAILABLE:{code:"10",msg:"Service Currently Unavailable"}  
  19.                                ,INSUFFICIENT_ISV_PERMISSIONS:{code:"11",msg:"Insufficient ISV Permissions"}  
  20.                                ,INSUFFICIENT_USER_PERMISSIONS:{code:"12",msg:"Insufficient User Permissions"}  
  21.                                ,INSUFFICIENT_PARTNER_PERMISSIONS:{code:"13",msg:"Insufficient Partner Permissions"}  
  22.                                ,REMOTE_SERVICE_ERROR:{code:"15",msg:"Remote service error"}  
  23.                                ,MISSING_METHOD:{code:"21",msg:"Missing Method"}  
  24.                                ,INVALID_METHOD:{code:"22",msg:"Invalid Method"}  
  25.                                ,INVALID_FORMAT:{code:"23",msg:"Invalid Format"}  
  26.                                ,MISSING_SIGNATURE:{code:"24",msg:"Missing Signature"}  
  27.                                ,INVALID_SIGNATURE:{code:"25",msg:"Invalid Signature"}  
  28.                                ,MISSING_SESSION:{code:"26",msg:"Missing session"}  
  29.                                ,INVALID_SESSION:{code:"27",msg:"Invalid Session"}  
  30.                                ,MISSING_APP_KEY:{code:"28",msg:"Missing App Key"}  
  31.                                ,INVALID_APP_KEY:{code:"29",msg:"Invalid App Key"}  
  32.                                ,MISSING_TIMESTAMP:{code:"30",msg:"Missing Timestamp"}  
  33.                                ,INVALID_TIMESTAMP:{code:"31",msg:"Invalid Timestamp"}  
  34.                                ,MISSING_VERSION:{code:"32",msg:"Missing Version"}  
  35.                                ,INVALID_VERSION:{code:"33",msg:"Invalid Version"}  
  36.                                ,UNSUPPORTED_VERSION:{code:"34",msg:"Unsupported Version"}  
  37.                                ,MISSING_REQUIRED_ARGUMENTS:{code:"40",msg:"Missing required arguments"}  
  38.                                ,INVALID_ARGUMENTS:{code:"41",msg:"Invalid arguments"}  
  39.                                ,FORBIDDEN_REQUEST:{code:"42",msg:"Forbidden Request"}  
  40.                                ,PARAMETER_ERROR:{code:"43",msg:"Parameter Error"}  
  41.                                ,INVALID_ENCODING:{code:"47",msg:"Invalid encoding"}  
  42.                                ,MISSING_TARGET:{code:"50",msg:"Missing Target"}  
  43.                                ,MISSING_LICENSE:{code:"51",msg:"Missing License"}  
  44.                                ,MISSING_APPPARAMS:{code:"52",msg:"Missing AppParams"}  
  45.                                ,INVALID_LICENSE2TARGET:{code:"53",msg:"Invalid License To Target"}  
  46.                                ,INVALID_NODE:{code:"54",msg:"Invalid Node"}  
  47.                                ,OVERTIME_SESSIONKEY:{code:"100",msg:"overtime session key "}  
  48.                                ,INVALID_SESSIONKEY:{code:"101",msg:"invalid session key"}  
  49.                                ,NOTMATCH_APP_KEY:{code:"108",msg:"app key is not match user"}  
  50.                                ,ThirdPlatform_UNKNOW_ERROR:{code:"102",msg:"unknow error from third platform"}  
  51.                     } 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章