Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  64] [ 5]  / answers: 1 / hits: 20991  / 15 Years ago, thu, january 14, 2010, 12:00:00

How can I use java to get a js file located on a web server, then execute the function in the js file and get the result and use the result in java.



Can you guys give me some code snippet? Great thanks.


More From » java

 Answers
93

There's three steps to this process:



  1. Fetch the JS file from the server.

  2. Execute some JS function from the file.

  3. Extract the result.


The first step is fairly simple, there are lots of HTTP libraries in Java that will do this - you effectively want to emulate the simple functionality of something like wget or curl. The exact manner in which you do this will vary depending on what format you want the JS file in for the next step, but the process to get hold of the byte stream is straightforward.


The second step will require executing the JS in a Javascript engine. Java itself cannot interpret Javascript, so you'd need to obtain an engine to run it in - Rhino is a common choice for this. Since you'd need to run this outside of Java, you'll likely have to spawn a process for execution in Rhino using ProcessBuilder. Additionally, depending on the format of the Javascript you might need to create your own "wrapper" javascript that functions like a main class in Java and calls the method in question.


Finally you need to get the result out - obviously you don't have direct access to JavaScript objects from your Java program. The easiest way is going to be for the JS program to print the result to standard out (possibly serialising as something like JSON depending on the complexity of the object), which is being streamed directly to your Java app due to the way you launched the Rhino process. This could be another job for your JS wrapper script, if any. Otherwise, if the JS function has observable side effects (creates a file/modifies a database) then you'll be able to query those directly from Java.


Job done.


I hope you realise this question is far too vague to get full answers. Asking the public to design an entire system goes beyond the point where you'll get useful, actionable responses.


[#97830] Tuesday, January 12, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;