I have javascript file (jalali.js) which it have a lot of functions. I want to call one of this functions in my java web application project (I mean somefile.Class file)
I had some research and i found these two methods:
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.eval("print('Hello, World')");
But I can not understand how to call my js file (jalali.js) and how should i call my function
I will put function detail code here (from jalali.js)
JalaliDate.gregorianToJalali = function(g_y, g_m, g_d)
{
g_y = parseInt(g_y);
g_m = parseInt(g_m);
g_d = parseInt(g_d);
var gy = g_y-1600;
var gm = g_m-1;
var gd = g_d-1;
...
...
return [jy, jm, jd];
}
I want to use that function in my java application (MyClass.class)
public class TaskListModel extends BaseModel{
private Date gDate;
private String jalaliDate;
public void setGDate(Date gDate) {
this.gDate= gDate;
this.jalaliDate = Here i need call the js function ;
}
-
3Rewrite the function/Port the script to Java? Is it that complicated?nhahtdh– nhahtdh2013年03月17日 08:53:58 +00:00Commented Mar 17, 2013 at 8:53
-
I agree... The syntax is quite similar, shouldn't be that difficult especially if you're a java guyOzzy– Ozzy2013年03月17日 08:55:00 +00:00Commented Mar 17, 2013 at 8:55
-
@Ozzy as i said this js file have a lot of functions . i can not copy/paste all the code to my java class file ... i have to call them . any solution?Masoud Sahabi– Masoud Sahabi2013年03月17日 09:05:27 +00:00Commented Mar 17, 2013 at 9:05
2 Answers 2
Well if this is the Rhino engine from 1.6 Java, then you can evaluate the code in jalali.js line by line - keeping the instance of engine alive through the runtime of the file. Also you can then execute the function like this: engine.eval("myfunction(arg1, arg2);");
I am not sure what you are trying to achieve
Step1. Read a line of the jalali.js file
Step2. engine.eval() the line
Step3. check if EOF - if yes, go to Step4 else go to Step1
Step4. engine.eval("your_function(arg1, arg2);");
3 Comments
jalali.js. Functions can be "called" files should be "parsed"a simple solution would be you read the whole file and append to it the function call you want to make and pass the modified contents to the eval method. so the final content passed to eval would take the form of
//
script in your .js file
//
return functionInYourJs(arg1, arg2);
Probably once the file is read you can cache it to avoid repeated disk reads.