4

I have a problem: I have to execute a phantomjs script in java program but I can't. this is the code of the script:

var page = require('webpage').create();
page.open('http://stackoverflow.com',function(status){
if(status !== 'success'){
    console.log('Open failed');
}else{
   console.log(page.evaluate(function(){
        return document.documentElement.outerHTML;
   }));
} 
phantom.exit();
});

In practice, I want to execute the javascript of a web page and after take the html resultant. I tried with the code at this link Running Phantomjs from javascript, JSP or Java but my program is blocked at this line

int exitStatus = process.waitFor();

what can I do to resolve this??

Thanks

Community
  • 1
  • 1
Frank Cunningham
  • 178
  • 1
  • 12
  • Are you running under an unix-like OS? Do you have installed PhantomJS and the script under /usr/bin? – Ortomala Lokni Jan 04 '15 at 10:58
  • 2
    The output of you phantomjs script is potentially long -- longer than the buffer size of Java's BufferedReader. You hence may fall into the trap that your phantomjs script blocks because you are not reading its output and the buffer is full. Check this for details: http://stackoverflow.com/questions/5483830/process-waitfor-never-returns – Miichi Jan 04 '15 at 11:11
  • yes I'm under unix-system (Ubuntu), phantomjs is installed and the script is in the same directory. – Frank Cunningham Jan 04 '15 at 13:35
  • I'd break the problem down into smaller ones. First, you should execute your phantom script from the command line to be sure it's returning what you expect. Then make sure you are executing phantom correctly from java. Use one of the simpler samples it comes with and just look for a return code, instead of a bunch of content. Once you know that java can find the phantom binary and that it's executing the script correctly, then you can look at the java end of things, in which case you may be running into the problem that Miichi mentions. – Matt Guest Jan 04 '15 at 14:41
  • the script working correctly. If I execute only the script from the command line I obtain what I what. The problem is to call this script in Java program... I can't do this. – Frank Cunningham Jan 04 '15 at 20:19

1 Answers1

3

You can use Runtime class to execute terminal commands. I was able to generate my desired output using below program.

Runtime rt = Runtime.getRuntime();
    try{
        Process pr = rt.exec("pathToPhantomHome/phantomjs "+ " pathToJSfile");
        BufferedInputStream bis = new BufferedInputStream(pr.getInputStream());
        bis.close();
    }catch(Exception ex){
        ex.printStackTrace();
    }
iCurious
  • 8,161
  • 7
  • 28
  • 46