create scriptable application

This tutorial will share how to create scriptable application on Openbravo ERP.  Many functionality achieved through scriptable application, for example : salary formula. Using scriptable application, user can define their salary formula by them self, make to flexible to end user.

ScriptEngine on Java is the best option to run JavaScript inside Java applications. Salary Formula saved into a text field that containing JavaScipt. This JavaScript will manipulate salary variable to perform salary formula evaluation resulting salary amount based on user defined formula.

You can refer to code snippets below:

package org.salaryformula;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class SalaryCalculator {

public static void main(String[] args) throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine se = mgr.getEngineByName("JavaScript");
se.put("index", 1400);
se.put("poin", 1200);
String formula = "var result= index*poin;";
se.eval(formula);
Bindings bindings = se.getBindings(ScriptContext.ENGINE_SCOPE);
String result = bindings.get("result").toString();
double basicsalary = Double.parseDouble(result);
System.err.println("basic salary: "+basicsalary);
se.put("basicsalary", basicsalary);
formula = "var result=0; var level1=0.05; var level2=0.15; if (basicsalary<1500000) result=basicsalary*level1; else result=basicsalary*level2;";
se.eval(formula);
bindings = se.getBindings(ScriptContext.ENGINE_SCOPE);
result = bindings.get("result").toString();
double incometax = Double.parseDouble(result);
System.err.println("income tax: "+incometax);
}
}

In the code above, you can see formula of basic salary is index x point, this formula is not embedded as a part of Java code, but saved onto string variable. Later, this variable can store a value from database field that managed by end user. Using eval method on ScriptEngine, Java evaluate Javascript code, then send result to Bindings object.

Now end user have highest degree of flexibility in determining how salary calculated. Later you can provide end user with set of internal variable that precomputed before salary formula evaluated. This will make salary formula development lots easier.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s