How to use AbstractAnnotations class of org.openqa.selenium.support.pagefactory package

Best Selenium code snippet using org.openqa.selenium.support.pagefactory.AbstractAnnotations

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package com.wYne.automation.ui.internal;
2
3import org.openqa.selenium.By;
4import org.openqa.selenium.SearchContext;
5import org.openqa.selenium.WebElement;
6import org.openqa.selenium.support.pagefactory.AbstractAnnotations;
7import org.openqa.selenium.support.pagefactory.Annotations;
8import org.openqa.selenium.support.pagefactory.ElementLocator;
9
10import java.lang.reflect.Field;
11import java.util.List;
12
13public class SlDefaultElementLocator implements ElementLocator {
14    private final SearchContext searchContext;
15    private final boolean shouldCache;
16    private final By by;
17    private WebElement cachedElement;
18    private List<WebElement> cachedElementList;
19
20    /**
21     * Creates a new element locator.
22     *
23     * @param searchContext The context to use when finding the element
24     * @param field The field on the Page Object that will hold the located value
25     */
26    public SlDefaultElementLocator(SearchContext searchContext, Field field) {
27        this(searchContext, new Annotations(field));
28    }
29
30    /**
31     * Use this constructor in order to process custom annotaions.
32     *
33     * @param searchContext The context to use when finding the element
34     * @param annotations AbstractAnnotations class implementation
35     */
36    public SlDefaultElementLocator(SearchContext searchContext, AbstractAnnotations annotations) {
37        this.searchContext = searchContext;
38        this.shouldCache = annotations.isLookupCached();
39        this.by = annotations.buildBy();
40    }
41
42    /**
43     * Find the element.
44     */
45    public WebElement findElement() {
46        if (cachedElement != null && shouldCache) {
47            return cachedElement;
48        }
49
50        WebElement element = searchContext.findElement(by);
51        if (shouldCache) {
52            cachedElement = element;
53        }
54
55        return element;
56    }
57
58    /**
59     * Find the element list.
60     */
61    public List<WebElement> findElements() {
62        if (cachedElementList != null && shouldCache) {
63            return cachedElementList;
64        }
65
66        List<WebElement> elements = searchContext.findElements(by);
67        if (shouldCache) {
68            cachedElementList = elements;
69        }
70
71        return elements;
72    }
73
74    @Override
75    public String toString(){
76        return this.getClass().getSimpleName() + " '" + by + "'";
77    }
78}
79
Full Screen
copy
1package com.diggavi.pageelements;
2
3import java.util.List;
4
5import org.openqa.selenium.SearchContext;
6import org.openqa.selenium.WebDriver;
7import org.openqa.selenium.WebElement;
8import org.openqa.selenium.support.pagefactory.AbstractAnnotations;
9import org.openqa.selenium.support.pagefactory.DefaultElementLocator;
10import org.openqa.selenium.support.pagefactory.ElementLocator;
11
12public class PageElementLocator extends DefaultElementLocator implements ElementLocator {
13	SearchContext searchContext;
14
15	public PageElementLocator(SearchContext searchContext, AbstractAnnotations annotations) {
16		super(searchContext, annotations);
17		this.searchContext = searchContext;
18	}
19
20	@Override
21	public PageElement findElement() {
22		WebElement element = super.findElement();
23		return new AbstractPageElement(element, ((WebDriver) searchContext));
24	}
25
26	@Override
27	public List<WebElement> findElements() {
28		return super.findElements();
29	}
30
31}
32
Full Screen
copy
1package ua.com.epam.decorator;
2
3import org.openqa.selenium.By;
4import org.openqa.selenium.WebElement;
5import org.openqa.selenium.support.pagefactory.AbstractAnnotations;
6import org.openqa.selenium.support.pagefactory.Annotations;
7import org.openqa.selenium.support.pagefactory.ElementLocator;
8import ua.com.epam.factory.DriverProvider;
9
10import java.lang.reflect.Field;
11import java.util.List;
12
13public class PageElementLocatorImpl implements ElementLocator {
14    private final DriverProvider provider;
15    private final boolean shouldCache;
16    private final By by;
17    private WebElement cachedElement;
18    private List<WebElement> cachedElementList;
19
20    public PageElementLocatorImpl(DriverProvider provider1, Field field) {
21        this(provider1, new Annotations(field));
22    }
23
24    public PageElementLocatorImpl(DriverProvider provider, AbstractAnnotations annotations) {
25        this.provider = provider;
26        this.shouldCache = annotations.isLookupCached();
27        this.by = annotations.buildBy();
28    }
29
30    public WebElement findElement() {
31        if (this.cachedElement != null && this.shouldCache()) {
32            return this.cachedElement;
33        } else {
34            WebElement element = this.provider.get().findElement(this.by);
35            if (this.shouldCache()) {
36                this.cachedElement = element;
37            }
38
39            return element;
40        }
41    }
42
43    public List<WebElement> findElements() {
44        if (this.cachedElementList != null && this.shouldCache()) {
45            return this.cachedElementList;
46        } else {
47            List<WebElement> elements = this.provider.get().findElements(this.by);
48            if (this.shouldCache()) {
49                this.cachedElementList = elements;
50            }
51
52            return elements;
53        }
54    }
55
56    protected boolean shouldCache() {
57        return this.shouldCache;
58    }
59
60    public String toString() {
61        return this.getClass().getSimpleName() + " '" + this.by + "'";
62    }
63}
64
Full Screen
copy
1static final String xpath;
2xpath=config.getsubmit(); 
3@FindBy(xpath)
4WebElement submit;
5
Full Screen
copy
1Public class WebElementRepo 
2{
3static WebElement01 = null;
4
5// then create getter setter for all these webelements
6
7public static void setWebElement01(WebElement WE)
8{
9WebElement01 = WE;
10}
11
12public static WebElement getWebElement01(WebElement WE)
13{
14return WebElement01;
15}
16
17}
18
Full Screen
copy
1WebElement element = driver.findElement(By.xpath(config.getsubmit()));
2
Full Screen
copy
1[
2  {
3    "pageName": "HomePage",
4    "name": "abTesting",
5    "locateUsing": "xpath",
6    "locator": "//a[contains(@href,'abtest')]"
7  },
8  {
9    "pageName": "HomePage",
10    "name": "checkBox",
11    "locateUsing": "xpath",
12    "locator": "//a[contains(@href,'checkboxes')]"
13  },
14  {
15    "pageName": "CheckboxPage",
16    "name": "checkBox1",
17    "locateUsing": "xpath",
18    "locator": "//input[@type='checkbox'][1]"
19  },
20  {
21    "pageName": "CheckboxPage",
22    "name": "checkBox2",
23    "locateUsing": "xpath",
24    "locator": "//input[@type='checkbox'][2]"
25  }
26]
27
Full Screen
copy
1import java.lang.annotation.ElementType;
2import java.lang.annotation.Retention;
3import java.lang.annotation.RetentionPolicy;
4import java.lang.annotation.Target;
5
6@Retention (RetentionPolicy.RUNTIME)
7@Target (ElementType.FIELD)
8public @interface SearchWith {
9    String inPage() default "";
10
11    String locatorsFile() default "";
12
13    String name() default "";
14}
15
Full Screen
copy
1import org.openqa.selenium.By;
2import org.openqa.selenium.SearchContext;
3import org.openqa.selenium.WebElement;
4import org.openqa.selenium.support.pagefactory.AbstractAnnotations;
5import org.openqa.selenium.support.pagefactory.ElementLocator;
6
7import java.util.List;
8
9public class FileBasedElementLocator implements ElementLocator {
10
11    private final SearchContext searchContext;
12    private final boolean shouldCache;
13    private final By by;
14    private WebElement cachedElement;
15    private List<WebElement> cachedElementList;
16
17
18    public FileBasedElementLocator(SearchContext searchContext, AbstractAnnotations annotations) {
19        this.searchContext = searchContext;
20        this.shouldCache = annotations.isLookupCached();
21        this.by = annotations.buildBy();
22    }
23
24    @Override
25    public WebElement findElement() {
26        if (cachedElement != null && shouldCache) {
27            return cachedElement;
28        }
29
30        WebElement element = searchContext.findElement(by);
31        if (shouldCache) {
32            cachedElement = element;
33        }
34
35        return element;
36
37    }
38
39    @Override
40    public List<WebElement> findElements() {
41        if (cachedElementList != null && shouldCache) {
42            return cachedElementList;
43        }
44
45        List<WebElement> elements = searchContext.findElements(by);
46        if (shouldCache) {
47            cachedElementList = elements;
48        }
49
50        return elements;
51    }
52}
53
Full Screen
copy
1import org.openqa.selenium.SearchContext;
2import org.openqa.selenium.support.pagefactory.ElementLocator;
3import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;
4
5import java.lang.reflect.Field;
6
7public class FileBasedElementLocatorFactory implements ElementLocatorFactory {
8    private final SearchContext searchContext;
9
10    public FileBasedElementLocatorFactory(SearchContext searchContext) {
11        this.searchContext = searchContext;
12    }
13
14    @Override
15    public ElementLocator createLocator(Field field) {
16        return new FileBasedElementLocator(searchContext, new CustomAnnotations(field));
17    }
18}
19
Full Screen
copy
1import com.google.common.base.Preconditions;
2import com.google.gson.JsonArray;
3import com.google.gson.JsonElement;
4import com.google.gson.JsonObject;
5import com.google.gson.JsonParser;
6import org.openqa.selenium.By;
7import org.openqa.selenium.support.CacheLookup;
8import org.openqa.selenium.support.pagefactory.AbstractAnnotations;
9import organized.chaos.annotations.SearchWith;
10
11import java.io.File;
12import java.io.FileNotFoundException;
13import java.io.FileReader;
14import java.lang.reflect.Field;
15import java.util.Iterator;
16
17class CustomAnnotations extends AbstractAnnotations {
18    private final Field field;
19
20    CustomAnnotations(Field field) {
21        this.field = field;
22    }
23
24    @Override
25    public By buildBy() {
26        SearchWith search = field.getAnnotation(SearchWith.class);
27        Preconditions.checkArgument(search != null, "Failed to locate the annotation @SearchWith");
28        String elementName = search.name();
29        String pageName = search.inPage();
30        String locatorsFile = search.locatorsFile();
31        Preconditions
32            .checkArgument(isNotNullAndEmpty(elementName), "Element name is not found.");
33        Preconditions.checkArgument(isNotNullAndEmpty(pageName), "Page name is missing.");
34        Preconditions.checkArgument(isNotNullAndEmpty(locatorsFile), "Locators File name not provided");
35        File file = new File(locatorsFile);
36        Preconditions.checkArgument(file.exists(), "Unable to locate " + locatorsFile);
37        try {
38            JsonArray array = new JsonParser().parse(new FileReader(file)).getAsJsonArray();
39            Iterator&amp;lt;JsonElement&amp;gt; iterator = array.iterator();
40            JsonObject foundObject = null;
41            while (iterator.hasNext()) {
42                JsonObject object = iterator.next().getAsJsonObject();
43                if (pageName.equalsIgnoreCase(object.get("pageName").getAsString()) &&
44                    elementName.equalsIgnoreCase(object.get("name").getAsString())) {
45                    foundObject = object;
46                    break;
47                }
48            }
49            Preconditions.checkState(foundObject != null, "No entry found for the page [" + pageName + "] in the "
50                + "locators file [" + locatorsFile + "]");
51            String locateUsing = foundObject.get("locateUsing").getAsString();
52            if (! ("xpath".equalsIgnoreCase(locateUsing))) {
53                throw new UnsupportedOperationException("Currently " + locateUsing + " is NOT supported. Only xPaths "
54                    + "are supported");
55            }
56
57            String locator = foundObject.get("locator").getAsString();
58            Preconditions.checkArgument(isNotNullAndEmpty(locator), "Locator cannot be null (or) empty.");
59            return new By.ByXPath(locator);
60        } catch (FileNotFoundException e) {
61            throw new RuntimeException(e);
62        }
63
64    }
65
66    @Override
67    public boolean isLookupCached() {
68        return (field.getAnnotation(CacheLookup.class) != null);
69    }
70
71    private boolean isNotNullAndEmpty(String arg) {
72        return ((arg != null) && (! arg.trim().isEmpty()));
73    }
74}
75
Full Screen
copy
1import org.openqa.selenium.WebElement;
2import organized.chaos.annotations.SearchWith;
3
4public class HomePage {
5    public static final String PAGE = "HomePage";
6    @SearchWith (inPage = HomePage.PAGE, locatorsFile = "src/main/resources/locators.json", name = "abTesting")
7    private WebElement abTestingLink = null;
8
9    @SearchWith (inPage = HomePage.PAGE, locatorsFile = "src/main/resources/locators.json", name = "checkBox")
10    private WebElement checkBoxLink = null;
11
12    public HomePage() {
13    }
14
15    public CheckBoxPage navigateToCheckBoxPage() {
16        checkBoxLink.click();
17        return new CheckBoxPage();
18    }
19}
20
Full Screen
copy
1import org.openqa.selenium.WebElement;
2import organized.chaos.annotations.SearchWith;
3
4public class CheckBoxPage {
5    private static final String PAGE = "CheckBoxPage";
6
7    @SearchWith (inPage = CheckBoxPage.PAGE, locatorsFile = "src/main/resources/locators.json", name = "checkBox1")
8    private WebElement checkBoxOne;
9
10    @SearchWith (inPage = CheckBoxPage.PAGE, locatorsFile = "src/main/resources/locators.json", name = "checkBox2")
11    private WebElement checkBoxTwo;
12
13    public void unCheckCheckBoxTwo() {
14        if (checkBoxTwo.isSelected()) {
15            checkBoxTwo.click();
16        }
17    }
18
19    public boolean isCheckBoxTwoUnchecked() {
20        return (! checkBoxTwo.isSelected());
21    }
22}
23
Full Screen
copy
1import org.openqa.selenium.chrome.ChromeDriver;
2import org.openqa.selenium.remote.RemoteWebDriver;
3import org.openqa.selenium.support.PageFactory;
4import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;
5import org.testng.Assert;
6import org.testng.annotations.AfterClass;
7import org.testng.annotations.BeforeClass;
8import org.testng.annotations.Test;
9import organized.chaos.pages.CheckBoxPage;
10import organized.chaos.pages.HomePage;
11import organized.chaos.support.FileBasedElementLocatorFactory;
12
13public class AlteredPageFactoryDemo {
14
15    private RemoteWebDriver driver;
16
17    @BeforeClass
18    public void setup() {
19        driver = new ChromeDriver();
20    }
21
22    @AfterClass
23    public void tearDown() {
24        if (driver != null) {
25            driver.quit();
26        }
27    }
28
29    @Test
30    public void testMethod() {
31        driver.get("https://the-internet.herokuapp.com/");
32        HomePage homePage = new HomePage();
33        ElementLocatorFactory factory = new FileBasedElementLocatorFactory(driver);
34        PageFactory.initElements(factory, homePage);
35        CheckBoxPage checkboxPage = homePage.navigateToCheckBoxPage();
36        PageFactory.initElements(factory, checkboxPage);
37        checkboxPage.unCheckCheckBoxTwo();
38        Assert.assertTrue(checkboxPage.isCheckBoxTwoUnchecked());
39    }
40}
41
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

...Most popular Stackoverflow questions on AbstractAnnotations

Most used methods in AbstractAnnotations

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)