java cometD + selenium。客户沟通不稳定

时间:2016-05-19 10:31:41

标签: java selenium tomcat cometd

我的计划: ajax对Tomcat的长轮询。 Tomcat执行selenium“operations”

我试图从tomcat执行selenium场景。 它的工作正常,但我需要将日志返回给js客户端。 当selenium工作时,Javascript客户端部分地从服务器接收消息。 在一些selenium操作中我使用 Thread.sleep()。也许是因为这个错误? 请告诉我为什么消息部分收到(我认为)客户

这是 ServerInfoLogger 。 BaseLogger将消息输出到控制台和文件

public class ServerInfoLogger extends BaseLogger {
    public ServerSession clientServerSession;

    protected void logToClient(String message) {
        super.log(message);
        sendMessage(message);
    }

    // Server.serverSession and Server.clientServerSession not null but messages partially not received by client
    private void sendMessage(String message) {
        // send message to client
        if (Server.serverSession!=null && Server.clientServerSession!=null) {
            Server.clientServerSession.deliver(Server.serverSession, "/message", message);
        } else {
            System.err.println("Server error. Server.serverSession=" + Server.serverSession + " clientServerSession=" + clientServerSession);
        }
    }
}

这是 selenium场景

public class Task extends ServerInfoLogger {
    public static boolean datesAvailable = false;
    private TaskParser parser = new TaskParser();
    protected ArrayList<Step> steps = new ArrayList<>();
    private WebDriver webDriver;
    protected int currentStepIndex = 0;
    protected Step currentStep;
    private WebDriverFactory webDriverFactory = new WebDriverFactory();
    private int currentTryout = 1;
    private int maxTryouts = 40;

    public Task(ServerSession clientServerSession, String taskData) {
        this.clientServerSession = clientServerSession;

        logToClient("new task"); // client always receives this message
        steps = parser.parse(taskData);
        logToClient("steps parsed. total: "+steps.size()); // client always receives this message
        start();
    }

    protected void start() {
        createWebDriver();
        startStep();
    }

    protected void startStep() {
        currentStep = steps.get(currentStepIndex);
        currentStep.setWebDriver(webDriver);
        currentStep.clientServerSession = clientServerSession;

        boolean stepComplete = false;

        try {
            stepComplete = currentStep.start();
        } catch (StepException e) {
            logToClient(e.getMessage()+"  step id: "+e.getStepId());
            e.printStackTrace();
        }

        log("step complete = "+stepComplete);

        if (stepComplete) {
            onStepComplete();
        } else {
            onStepError();
        }
    }

    private void onStepError() {
        currentTryout++;
        if (currentTryout > maxTryouts) {
            destroyWebDriver();
            logToClient("Max tryouts reached"); // client never receives this message
        } else {
            logToClient("Step not complete. Restarting task. currentTryout=" + currentTryout); // client partially receives this message
            restart();
        }
    }

    private void onStepComplete() {
        currentStepIndex++;
        if (currentStepIndex < steps.size()) {
            startStep();
        } else {
            destroyWebDriver();
            taskComplete();
        }
    }

    private void destroyWebDriver() {
        webDriver.quit();
        webDriver = null;
    }

    private void taskComplete() {
        logToClient("Task complete !!!"); // client **never** receives this message
        TaskEvent taskEvent = new TaskEvent(TaskEvent.TASK_COMPLETE);
        EventDispatcher.getInstance().dispatchEvent(taskEvent);
    }

    public void restart() {
        logToClient("Task restart");
        try {
            setTimeout(Application.baseOperationWaitSecondsUntil);
            new SwitchToDefaultContentOperation().execute();
        } catch(OperationException exception) {
            logToClient("Cannot get default content"); // client partially receives this message
        }
        currentStepIndex = 0;
        startStep();
    }

    private void setTimeout(int seconds) {
        webDriver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS);
    }

    private void createWebDriver() {
        webDriver = webDriverFactory.getDriver(BrowserType.CHROME).getDriver();
    }

    public int getCurrentStepIndex() {
        return currentStepIndex;
    }
}

以下是记录器

的创建
private void createLogger() {
    Date currentDate = new Date();

    String logFilePostfix = currentDate.getMonth()+"_"+currentDate.getDate()+"-"+currentDate.getHours()+"_"+currentDate.getMinutes()+"_"+currentDate.getSeconds();

    logger = Logger.getLogger(appName); 
    logger.setUseParentHandlers(false);
    FileHandler fh; 

    SimplestFormatter formatter = new SimplestFormatter();

    try {  
        fh = new FileHandler("C:\\consultant\\logs\\log_"+logFilePostfix+".txt");
        logger.addHandler(fh);
        fh.setFormatter(formatter);  
    } catch (SecurityException e) {  
        e.printStackTrace(); 
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
}

使用 Thread.sleep()

进行Selenium操作
public class SwitchToMainFrameOperation extends BaseOperation {
    private WebElement mainIframe; 
    private WebDriverWait wait;

    @Override
    public boolean execute() throws OperationException {
        switchToRoot();

        sleepThread();
        log("switchToMainIFrame by xPath "+Page.getMainIframeXPath()); // log to console and file

        wait = new WebDriverWait(webDriver, Application.baseOperationWaitSecondsUntil);

        try {
            mainIframe = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(Page.getMainIframeXPath())));
            webDriver.switchTo().frame(mainIframe);
            log("main frame switch OK"); // log to console and file
        } catch(StaleElementReferenceException exception) {
            log("main frame switch error. StaleElementReferenceException - trying again"); // log to console and file
            wait = null;
            sleepThread();
            execute();
        }

        return true;
    }

    private void switchToRoot() {
        log("switch to root");
        webDriver.switchTo().defaultContent();
    }

    private void sleepThread() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

0 个答案:

没有答案