Бэкэнд Java пытается запустить PhantomJS в AWS Linux - PullRequest
0 голосов
/ 13 декабря 2018

У меня проблема, которую я пытался решить месяцами, и не могу найти решение.Я пытаюсь запустить PhantomJS из бэкэнда Java, чтобы получить доступ к определенному URL, используя Quartz Job, а затем после создания файла отправив его по электронной почте, используя javax.mail.

Это прекрасно работает на моей локальной машине иЯ даже тестировал на AWS Windows Server, и он работает.Когда я пытаюсь выполнить развертывание на AWS Linux Server, я изменяю команду на bash, но даже если phantomjs завершается успешно, файл никогда не создается.Вот пример команды, которую я использую (я заменил фактические значения, чтобы сделать ее проще):

bash  -c "cd /usr/bin && phantomjs --web-security=false path_to_phantomjs_file/phantomreport.js 'some_url_in_here' PDF /tmp/filename"

У меня есть следующие параметры: - Путь к phantomreport.js файлу phantomsjsдля использования - URL, к которому я хочу получить доступ и сделать снимок экрана - Тип файла, в который я хочу экспортировать - Путь к папке, в которую я хочу сохранить файл, а также имя файла

Вот мой код phantomreport.js:

var system = require('system');
var page = require('webpage').create();
var fs = require('fs');
var systemargs = system.args;


if (systemargs.length === 1) {
  phantom.exit(2);
} else {
    var url = systemargs[1];
    var type = systemargs[2];
    var filename = systemargs[3];

var page = require('webpage').create();
page.viewportSize = {
  width: 1920,
  height: 1080
};

page.open(url, function(status) {
  if(status === "success"){
      waitFor(function() {
          return page.evaluate(function() {
              var el = document.getElementById("content");
              if(el.offsetParent !== null){
                 return true; 
              }
              return false;
          });
      }, function () {
        switch(type){
            case "PDF":
                // Saving diagram as PDF
                page.render(filename + '.pdf');
                break;
            case "PNG":
                // Saving diagram as PNG
                page.render(filename + '.png');
                break;
            case "JPEG":
                // Saving diagram to JPEG
                page.render(filename + '.jpeg');
                break;
            case "SVG":
                //Saving diagram to SVG
                fs.write(filename + ".svg", chart);
                break;
            case "CSV":
                //Saving diagram to CSV
                fs.write(filename + ".csv", chart);
                break;
            case "XLS":
                //Saving diagram to XLS
                fs.write(filename + ".xls", chart);
                break;
        }
        phantom.exit(1);
      });
  } else {
      console.log("Unable to access network");
      phantom.exit(2);
  }
});
}

/**
 * Wait until the test condition is true or a timeout occurs. Useful for waiting
 * on a server response or for a ui change (fadeIn, etc.) to occur.
 *
 * @param testFx javascript condition that evaluates to a boolean,
 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
 * as a callback function.
 * @param onReady what to do when testFx condition is fulfilled,
 * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or
 * as a callback function.
 * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used.
 */

"use strict";
function waitFor(testFx, onReady, timeOutMillis) {
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 30000, //< Default Max Timout is 3s / Set to 30 secs
        start = new Date().getTime(),
        condition = false,
        interval = setInterval(function() {
            if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
                // If not time-out yet and condition not yet fulfilled
                condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code
            } else {
                if(!condition) {
                    // If condition still not fulfilled (timeout but condition is 'false')
                    console.log("'waitFor()' timeout");
                    phantom.exit(2);
                } else {
                    // Condition fulfilled (timeout and/or condition is 'true')
                    console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms.");
                    typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled
                    clearInterval(interval); //< Stop this interval
                }
            }
        }, 250); //< repeat check every 250ms
}

Я проверил разрешения, правильно избежал косой черты.Все, что я могу придумать.Когда я запускаю его прямо на терминале, он работает нормально.Запуск из Java не работает, так как файл никогда не создается.

Буду признателен за помощь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...