Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package uk.sponte.automation.seleniumpom;
  
  import  org.openqa.selenium.By;
  import  org.openqa.selenium.SearchContext;
  import  org.openqa.selenium.WebDriver;
  import  org.openqa.selenium.WebElement;
  import  org.openqa.selenium.internal.Locatable;
  import  org.openqa.selenium.internal.WrapsElement;
 import  org.openqa.selenium.support.FindAll;
 import  org.openqa.selenium.support.FindBy;
 import  org.openqa.selenium.support.FindBys;
 import  org.openqa.selenium.support.pagefactory.Annotations;
 
 import java.util.*;

Selenium POM page factory - responsible for initialising pages with proxies Created by swozniak-ba on 02/04/15.
 
 public class PageFactory {
 
     public PageFactory() {
         this(new DefaultDependencyInjectorImpl());
     }
 
     public WebDriver getDriver() {
         return .get(WebDriver.class);
     }
 
     public PageFactory(DependencyInjector dependencyInjector) {
         this. = dependencyInjector;
     }
 
     public <T> T get(Class<T> pageClassthrows PageFactoryError {
         return this.get(pageClassgetDriver());
     }
 
     public <T> T get(T page) {
         return initializeContainer(pagegetDriver());
     }
 
     public <T> T get(Class<T> pageClass, SearchContext searchContextthrows PageFactoryError {
         T page = findImplementationBasedOnPageFilter(pageClass);
 
         return initializeContainer(pagesearchContext);
     }
 
     private <T> T findImplementationBasedOnPageFilter(Class<T> pageClass) {
         ImplementationFinder<T> implementationFinder = new ImplementationFinder<T>(pageClass);
         return implementationFinder.find();
     }
 
     private <T> T initializeContainer(T page, SearchContext searchContext) {
         setRootElement(pagesearchContext);
         for (Field field : ClassHelper.getFieldsFromClass(page.getClass())) {
             if(field.getName().equals("rootElement")) continue;
 
             initializePageElements(fieldpagesearchContext);
             initializePageSections(fieldpagesearchContext);
             initializeFrames(fieldpagesearchContext);
 
             initializePageElementLists(fieldpagesearchContext);
             initializePageSectionLists(fieldpagesearchContext);
         }
 
         return page;
     }
 
     private <T> void initializeFrames(Field field, T page, SearchContext searchContext) {
         Class<?> fieldType = field.getType();
         if(List.class.isAssignableFrom(fieldType)) return;
         if(field.getAnnotation(Frame.class) == nullreturn;
 
         WebDriver webDriver = getDriver();
         Annotations annotations = new Annotations(field);
 
         SearchContext frame = getFrameProxy(
                 webDriver,
                 annotations.buildBy(),
                searchContext,
                field);
        try {
            Object pageSection = .get(fieldType);
            this.initializeContainer(pageSectionframe);
            field.setAccessible(true);
            field.set(pagepageSection);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    private <T> void setRootElement(T pageObject, SearchContext searchContext) {
        if(!(searchContext instanceof PageElement)) return;
        try {
            Field rootElement = findField(pageObject.getClass(), "rootElement");
            rootElement.setAccessible(true);
            rootElement.set(pageObjectsearchContext);
        } catch (NoSuchFieldException e) {
            // e.printStackTrace();
        } catch (IllegalAccessException e) {
            throw new PageFactoryError(e.getCause());
        }
    }
    public Field findField(Class<?> klassString namethrows NoSuchFieldException {
        while(klass != null) {
            for (Field field : klass.getDeclaredFields()) {
                if (field.getName().equalsIgnoreCase(name))
                    return field;
            }
            klass = klass.getSuperclass();
        }
        throw new NoSuchFieldException("Could not find field with name " + name);
    }
    private <T> void initializePageSectionLists(Field field, T page, SearchContext searchContext) {
        if(!isValidPageSectionList(field))
            return;
        Type genericType = field.getGenericType();
        ParameterizedType genericTypeImpl = (ParameterizedTypegenericType;
        Type genericTypeArgument = genericTypeImpl.getActualTypeArguments()[0];
        Annotations annotations = new Annotations(field);
        PageSectionListHandler pageSectionListHandler = new PageSectionListHandler(
                getDriver(),
                searchContext,
                annotations.buildBy(),
                genericTypeArgument,
                this);
        Object proxyInstance = Proxy.newProxyInstance(
                Section.class.getClassLoader(),
                new Class[]{List.class},
                pageSectionListHandler
        );
        field.setAccessible(true);
        try {
            field.set(pageproxyInstance);
        } catch (IllegalAccessException e) {
            throw new PageFactoryError(e.getCause());
        }
    }
    private <T> void initializePageSections(Field field, T page, SearchContext searchContext) {
        if(!isValidPageSection(field)) return;
        WebDriver webDriver = getDriver();
        Annotations annotations = new Annotations(field);
        SearchContext container = getPageElementProxy(
                webDriver,
                annotations.buildBy(),
                searchContext,
                field);
        try {
            Object pageSection = .get(field.getType());
            this.initializeContainer(pageSectioncontainer);
            field.setAccessible(true);
            field.set(pagepageSection);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    @SuppressWarnings("RedundantIfStatement")
    private boolean isValidPageSection(Field field) {
        Class<?> fieldType = field.getType();
        if(List.class.isAssignableFrom(fieldType)) return false;
        if(PageElement.class.isAssignableFrom(fieldType)) return false;
        if(WebElement.class.isAssignableFrom(fieldType)) return false;
        if(field.getAnnotation(Section.class) != nullreturn true;
        if(PageSection.class.isAssignableFrom(fieldType)) return true;
        if(hasSeleniumFindByAnnotation(field)) return true;
        return false;
    }
    @SuppressWarnings("RedundantIfStatement")
    private boolean isValidPageSectionList(Field field) {
        // return false if it's not a list
        if (!List.class.isAssignableFrom(field.getType())) return false;
        // If we marked field with Section annotation, I'll assume you know what you're doing
        if (field.getAnnotation(Section.class) != nullreturn true;
        // If it's not generic, return false
        Type genericType = field.getGenericType();
        if (!(genericType instanceof ParameterizedType)) return false;
        ParameterizedType genericTypeImpl = (ParameterizedTypegenericType;
        Class<?> genericTypeArgument = (Class<?>) genericTypeImpl.getActualTypeArguments()[0];
        // PageElement list is not pageSection
        if (PageElement.class.isAssignableFrom(genericTypeArgument)) return false;
        if (PageSection.class.isAssignableFrom(genericTypeArgument)) return true;
        return false;
    }
    @SuppressWarnings("RedundantIfStatement")
    private boolean hasSeleniumFindByAnnotation(Field field) {
        if(field.getAnnotation(FindBy.class) != nullreturn true;
        if(field.getAnnotation(FindBys.class) != nullreturn true;
        if(field.getAnnotation(FindAll.class) != nullreturn true;
        return false;
    }
    private <T> void initializePageElementLists(Field field, T page, SearchContext searchContext) {
        Class<?> fieldType = field.getType();
        if (!List.class.isAssignableFrom(fieldType)) return;
        Type genericType = field.getGenericType();
        if (!(genericType instanceof ParameterizedType)) return;
        ParameterizedType genericTypeImpl = (ParameterizedTypegenericType;
        if (!PageElement.class.isAssignableFrom((Class<?>)genericTypeImpl.getActualTypeArguments()[0])) return;
        Annotations annotations = new Annotations(field);
        WebElementListHandler elementListHandler = new WebElementListHandler(searchContextannotations.buildBy());
        List webElementListProxy = (List) Proxy.newProxyInstance(
                WebElement.class.getClassLoader(),
                new Class[]{List.class},
                elementListHandler
        );
        ElementListImpl webElementListExtensions = new ElementListImpl(searchContextwebElementListProxy);
        InvocationHandler pageElementHandler = new ElementListHandler(webElementListProxywebElementListExtensions);
        List pageElementListProxy = (List) Proxy.newProxyInstance(
                PageElement.class.getClassLoader(),
                new Class[]{List.class},
                pageElementHandler);
        try {
            field.setAccessible(true);
            field.set(pagepageElementListProxy);
        } catch (IllegalAccessException e) {
            throw new PageFactoryError(e.getCause());
        }
    }
    private <T> void initializePageElements(Field field, T page, SearchContext searchContext) {
        if (PageElement.class.isAssignableFrom(field.getType())) {
            WebDriver webDriver = getDriver();
            Annotations annotations = new Annotations(field);
            try {
                PageElement pageElementProxy = getPageElementProxy(webDriverannotations.buildBy(), searchContextfield);
                field.setAccessible(true);
                field.set(pagepageElementProxy);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    private PageElement getPageElementProxy(WebDriver driver, By by, SearchContext searchContextField field) {
        WebElementHandler elementHandler = new WebElementHandler(driversearchContextby);
        WebElement proxyElement = (WebElement) Proxy.newProxyInstance(
                WebElement.class.getClassLoader(),
                new Class[]{WebElement.class, Locatable.class,SearchContext.class, WrapsElement.class },
                elementHandler
        );
        PageElementImpl pageElement = new PageElementImpl(driverproxyElement);
        InvocationHandler pageElementHandler = new ElementHandler(driverproxyElementpageElement);
        return (PageElement) Proxy.newProxyInstance(
                PageElement.class.getClassLoader(),
                new Class[]{PageElement.class},
                pageElementHandler);
    }
    private PageElement getFrameProxy(WebDriver driver, By by, SearchContext searchContextField field) {
        // Handles return frameObject
        WebElementHandler elementHandler = new WebElementHandler(driversearchContextby);
        WebElement frameElement = (WebElement) Proxy.newProxyInstance(
                WebElement.class.getClassLoader(),
                new Class[]{WebElement.class, Locatable.class,SearchContext.class, WrapsElement.class },
                elementHandler
        );
        // Handles return frameObject
        WebElementHandler bodyHandler = new WebElementHandler(driversearchContext, By.tagName("body"));
        WebElement bodyElement = (WebElement) Proxy.newProxyInstance(
                WebElement.class.getClassLoader(),
                new Class[]{WebElement.class, Locatable.class,SearchContext.class, WrapsElement.class },
                bodyHandler
        );
        PageElementImpl pageElement = new PageElementImpl(driverbodyElement);
        pageElement.frame = frameElement;
        InvocationHandler pageElementHandler = new ElementHandler(driverbodyElementpageElementframeElement);
        return (PageElement) Proxy.newProxyInstance(
                PageElement.class.getClassLoader(),
                new Class[]{PageElement.class},
                pageElementHandler);
    }
New to GrepCode? Check out our FAQ X