java公式解析(BeanShell + commons-digester)

來源:互聯網
上載者:User

java公式解析(BeanShell + commons-digester)

部分代碼源於IBM BSH教程

2010.4.1. 10:42:58 @hz

 

formulas.xml

<?xml version="1.0" encoding="UTF-8"?><br /><formulas><br /><formula id="1001" name="F_DISCOUNT"><br /><resulttype>double</resulttype><br /><parameters><br /><parameter type="double" name="price"/><br /><parameter type="double" name="discount"/><br /></parameters><br /><mce:script type="text/javascript"><!--<br />result= Calculator.mutiply(price, discount)<br />// --></mce:script><br /></formula><br /><formula id="1002" name="F_BONUS"><br /><resulttype>double</resulttype><br /><parameters><br /><parameter type="double" name="sale"/><br /><parameter type="double" name="score"/><br /></parameters><br /><mce:script type="text/javascript"><!--<br />result= Calculator.add(Calculator.mutiply(sale, 0.1),Calculator.mutiply(score, 10000))<br />// --></mce:script><br /></formula><br /></formulas><br />

 

 

formulas-rules.xml

 

<?xml version="1.0" encoding="UTF-8"?><br /><digester-rules><br /><pattern value="formulas"><br /><object-create-rule classname="my.test.study.bsh.Formulas" /><br /><pattern value="formula"><br /><bean-property-setter-rule pattern="resulttype" /><br /><object-create-rule classname="my.test.study.bsh.Formula" /><br /><set-properties-rule /><br /><pattern value="parameters/parameter"><br /><object-create-rule<br />classname="my.test.study.bsh.Parameter" /><br /><set-properties-rule /><br /><set-next-rule methodname="addParameter" /><br /></pattern><br /><bean-property-setter-rule pattern="script" /><br /><set-next-rule methodname="addFormula" /><br /></pattern><br /></pattern><br /></digester-rules>

 

 

Paramter.java

 

public class Parameter {<br />private String type;<br />private String name;<br />public String toString()<br />{<br />return this.type+" " + this.name;<br />}<br />}<br />

 

Formula.java

 

import java.util.Vector;</p><p>public class Formula {<br />private String id;</p><p>private String name;</p><p>private String resulttype;<br />private String script;</p><p>private Vector parameters;</p><p>public void addParameter(Parameter parameter) {<br />parameters.add(parameter);<br />}</p><p>public Formula() {<br />parameters = new Vector();<br />}</p><p>public String parametersToString()<br />{<br />StringBuffer _result=new StringBuffer("");<br />Object[] _paramsArray=parameters.toArray();<br />for(int _i=0; _i< _paramsArray.length;_i++)<br />{<br />if(_i!=0)<br />{<br />_result.append(",");<br />}<br />_result.append(((Parameter)_paramsArray[_i]).toString());<br />}<br />return _result.toString();<br />}</p><p>}<br />

 

 

Formulas.java

 

package my.test.study.bsh;</p><p>import java.io.IOException;<br />import java.net.URL;<br />import java.util.Hashtable;</p><p>import org.apache.commons.digester.Digester;<br />import org.apache.commons.digester.xmlrules.DigesterLoader;<br />import org.xml.sax.SAXException;</p><p>public class Formulas {<br />private final static URL formulasUrl=new Formulas().getClass().getClassLoader().getResource("formulas.xml");<br />private final static URL ruleUrl=new Formulas().getClass().getClassLoader().getResource("formulas-rules.xml");<br />public Hashtable formulas;<br />public Formulas()<br />{<br />formulas=new Hashtable();<br />}<br />public void addFormula(Formula f)<br />{<br />formulas.put(f.getId(), f);<br />}<br />public static Formulas getFormulasByBean()<br />{<br />Formulas result=new Formulas();<br />Digester digester=new Digester();<br />try {<br />digester.push(result);<br />digester.addObjectCreate("formulas/formula", Formula.class );<br />digester.addSetProperties("formulas/formula");<br />digester.addBeanPropertySetter("formulas/formula/resulttype", "resulttype");</p><p>digester.addObjectCreate("formulas/formula/parameters/parameter", Parameter.class );<br />digester.addSetProperties("formulas/formula/parameters/parameter");<br />digester.addSetNext("formulas/formula/parameters/parameter", "addParameter");</p><p>digester.addBeanPropertySetter("formulas/formula/script", "script");</p><p>digester.addSetNext("formulas/formula", "addFormula");<br />result=(Formulas)digester.parse(formulasUrl);<br />}<br />catch (IOException e) {<br />e.printStackTrace();<br />}<br />catch (SAXException e) {<br />e.printStackTrace();<br />}<br />return result;<br />}<br />public Formula loadFormulaByBean(String id) {<br />Formulas result=new Formulas();<br />return (Formula)result.getFormulasByBean().formulas.get(id);<br />}<br />public Formula loadFormulaByRules(String id) {<br />Formulas _formulas=new Formulas();<br />return (Formula)_formulas.getFormulasByRules().formulas.get(id);<br />}<br />public Formula loadFormula(String id) {<br />Formulas fa = new Formulas();<br />//return fa.loadFormulaByBean(id);<br /> return fa.loadFormulaByRules(id);<br />}<br />public static Formulas getFormulasByRules()<br />{<br />Formulas _formulas=new Formulas();<br />Digester digester;<br />try {<br />digester = DigesterLoader.createDigester(ruleUrl);<br />_formulas=(Formulas)digester.parse(formulasUrl);<br />}<br />catch (IOException e) {<br />e.printStackTrace();<br />}<br />catch (SAXException e) {<br />e.printStackTrace();<br />}<br />return _formulas;<br />}<br />}<br />

 

FormulaParser.java

 

import java.util.Enumeration;<br />import java.util.Hashtable;<br />import java.util.Iterator;<br />import java.util.Vector;</p><p>import bsh.Interpreter;</p><p>public class FormulaParser {<br />public double caculateByFormula(Formula formula, Hashtable parameters) {<br />double result = 0.0;<br />try {<br />Interpreter i = new Interpreter();<br />i.eval("import my.test.study.bsh.parse.*;");<br />Vector para = formula.getParameters();<br />Iterator it = para.iterator();<br />while (it.hasNext()) {<br />Parameter dec = (Parameter) it.next();<br />String declare = dec.getType() + " " + dec.getName();<br />i.eval(declare);<br />String value = ((Double) parameters.get(dec.getName())).toString();<br />if (value != null) {<br />String assign_value = dec.getName() + " = " + value;<br />System.out.println(assign_value);<br />i.eval(assign_value);<br />}<br />else {<br />System.out.println("caculateByFormula():" + dec.getName() + "參數名不符或改參數不存在");<br />System.exit(1);<br />}<br />}<br />System.out.println(formula.getScript());<br />i.eval(formula.getScript());<br />Double rst = (Double) i.get("result");<br />result = rst.doubleValue();<br />}<br />catch (Exception e) {<br />System.out.println("caculateByFormula():" + e.getMessage());<br />}<br />return result;<br />}</p><p>public Formula loadFormula(String id) {<br />Formulas fa = new Formulas();<br />// return fa.loadFormulaByBean(id);<br />return fa.loadFormulaByRules(id);<br />}<br />Formulas fa;<br />public FormulaParser()<br />{<br />if(fa==null) fa= new Formulas();<br />}</p><p>public static String mountAllFuction()<br />{<br />String clsHead="public class Formula{ /n/t";<br />String funcHead="public static ";<br />String funcBodyH="/n/t{/n/t/t return ";<br />String funcbodyE=";} /n/t";<br />StringBuffer result=new StringBuffer(clsHead);<br />Enumeration _e = Formulas.getFormulasByBean().formulas.elements();<br />//Enumeration _e = Formulas.getFormulasByRules().formulas.elements();</p><p>while(_e.hasMoreElements())<br />{<br />Formula _f=(Formula)_e.nextElement();<br />result.append(funcHead);<br />result.append(_f.getResulttype());<br />result.append(" "+_f.getName());<br />result.append("(");<br />result.append(_f.parametersToString());<br />result.append(")");<br />result.append(funcBodyH);<br />result.append(_f.getScript());<br />result.append(funcbodyE);<br />}<br />result.append("}");<br />return result.toString();<br />}</p><p>}<br />

 

TestParser.java

 

import java.util.Hashtable;</p><p>import bsh.EvalError;<br />import bsh.Interpreter;</p><p>public class TestParser {<br />public static void main(String args[])<br />{<br />FormulaParser fp= new FormulaParser();<br />Hashtable paras= new Hashtable();<br />paras.put("price", new Double(100.0));<br />paras.put("discount", new Double(0.9));<br />System.out.println("計算結果:"+ fp.caculateByFormula(fp.loadFormula("1001"), paras));<br />FormulaParser fp1= new FormulaParser();<br />Hashtable paras1= new Hashtable();<br />paras1.put("sale", new Double(11000.0));<br />paras1.put("score", new Double(0.8));<br />Formula fa=fp1.loadFormula("1002");<br />System.out.println("計算結果:"+ fp1.caculateByFormula(fa, paras1));<br />Interpreter i = new Interpreter();<br />String str="Calculator.add(Calculator.mutiply(11000.0, 0.1),Calculator.mutiply(0.8, 10000))";<br />// 執行個體化一個BeanShell解譯器<br />try {<br />i.eval("import my.test.study.bsh.parse.*;");<br />String result=i.eval(str).toString();<br />System.out.println(result);</p><p>String functions= fp.mountAllFuction();<br />i.eval(functions);<br />str="Formula.F_BONUS(11000.0,0.8)";<br />result=i.eval(str).toString();<br />System.out.println(functions);<br />System.out.println(result);<br />}<br />catch (EvalError e) {<br />e.printStackTrace();<br />}</p><p>}<br />}<br />

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.