au.unick.testing.oos.lazylocators.BaseLazyLocator.java Source code

Java tutorial

Introduction

Here is the source code for au.unick.testing.oos.lazylocators.BaseLazyLocator.java

Source

/*
Copyright 2011-2012 Nikolay Georgievskiy
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
 http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
    
*/
package au.unick.testing.oos.lazylocators;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public abstract class BaseLazyLocator {
    private BaseLazyLocator parent;
    private WebElement webElement = null;

    public BaseLazyLocator(BaseLazyLocator parent) {
        this.parent = parent;
    }

    /**
     * Create and return WebElement available from WebDriver by locator
     * @param wd
     * @return
     */
    public WebElement getElement(WebDriver wd) {
        if (webElement == null) {
            WebElement parentWebElement = getParentElement(wd);
            By by = by();
            if (null == by) {
                webElement = parentWebElement;
            } else if (null == parentWebElement) {
                webElement = wd.findElement(by);
            } else {
                webElement = parentWebElement.findElement(by);
            }
        }
        return webElement;
    }

    /**
     * Create and return list of WebElement available from WebDriver by locator
     * @param wd
     * @return
     */
    public List<WebElement> getElements(WebDriver wd) {
        WebElement parentWebElement = getParentElement(wd);
        By by = by();
        if (null == by) {
            return null; // shall it return parent element in this case? Arrays.asList( parentWebElement );
        }
        if (null == parentWebElement) {
            return wd.findElements(by);
        } else {
            return parentWebElement.findElements(by);
        }
    }

    /**
     * Update WebElement from WebDriver
     * @param wd
     */
    public void refresh(WebDriver wd) {
        webElement = null;
        if (null != parent) {
            parent.refresh(wd);
        }
        getElement(wd);
    }

    protected WebElement getParentElement(WebDriver wd) {
        return (null == parent) ? null : parent.getElement(wd);
    }

    public abstract By by();
}