com.testmax.handler.ElementHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.testmax.handler.ElementHandler.java

Source

/*
 * Copyright (C) 2014 Artitelly Solutions Inc, www.CloudTestSoftware.com
 *
 * Licensed under the Common Development and Distribution License (CDDL-1.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://opensource.org/licenses/CDDL-1.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 com.testmax.handler;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.testmax.exception.TestMaxException;
import com.testmax.framework.ConfigLoader;
import com.testmax.framework.WmLog;
import com.testmax.util.PrintTime;
import org.dom4j.Element;

public abstract class ElementHandler {

    protected HashMap<String, WebDriver> driverList = new HashMap<String, WebDriver>();
    private String tagname;
    private String controlIdentifier;
    protected String timeout = "";
    protected String threadIndex = "1";
    protected boolean isMultiThreaded = false;
    protected boolean isLogClosed = false;
    protected volatile WebDriver driver;
    BufferedWriter logfile = null;
    BufferedWriter commandlogfile = null;
    BufferedWriter xpathlogfile = null;
    protected String id = "";
    protected String name = "";
    protected String iframe = "";
    protected Element targetTag = null;
    protected boolean isIframe = false;
    protected boolean isIE = false;
    protected String trackId = null;
    protected String window = "";
    protected String tagName = "";
    protected String description = "";
    protected String tagdesc = "";
    protected PrintTime timer = null;
    protected String operation = "";
    //use having tags (can be comma seperated list) along with closest Id, Name, cssLocator or xpath of the target elements
    protected String havingTag = "";
    protected String havingText = "";
    protected String havingAlt = "";
    protected String havingImage = "";
    protected String havingLinkText = "";
    protected String havingName = "";
    protected String havingClassName = "";
    protected String havingOnClick = "";
    protected String havingHref = "";
    protected String havingAttribute = "";
    protected int detectionError = 0;
    protected boolean detectionByXpath = false;
    protected boolean isPopupFound = false;
    HashMap<String, String> popupscripts = new HashMap<String, String>();

    protected HashMap<String, String> getAttributesList() {
        HashMap<String, String> attribs = new HashMap<String, String>();

        this.controlIdentifier = " tagname=" + this.tagname + " and havingAttribute" + "=" + this.havingAttribute;
        String[] attrs = this.havingAttribute.split("#");
        for (String attr : attrs) {
            if (!attr.contains("xpath::")) {

                String[] attrvs = attr.split("::");
                if (attr.indexOf("=") >= 0) {
                    attrvs = attr.split("=");
                }
                if (attrvs.length == 2) {
                    attribs.put(attrvs[0].trim(), attrvs[1].trim());
                }
            }

        }
        return attribs;
    }

    protected HashMap<String, String> getAttributesList(String tagname, String havingattribute) {
        HashMap<String, String> attribs = new HashMap<String, String>();

        this.controlIdentifier = " tagname=" + this.tagname + " and havingAttribute" + "=" + havingattribute;
        String[] attrs = havingattribute.split("#");
        for (String attr : attrs) {
            if (!attr.contains("xpath::")) {

                String[] attrvs = attr.split("::");
                if (attr.indexOf("=") >= 0) {
                    attrvs = attr.split("=");
                }
                if (attrvs.length == 2) {
                    attribs.put(attrvs[0].trim(), attrvs[1].trim());
                }
            }

        }
        return attribs;
    }

    protected boolean executeScript(String script) {
        PrintTime timer = new PrintTime();

        try {
            setImpilicitTimeInMiliSec(new Integer(timeout));

            ((JavascriptExecutor) this.getDriver()).executeScript(script);
            printMessage("**** Executed Java Script " + timer.getPrintTime() + " Script=" + script);
            if (script.contains("click()")) {
                this.waitToPageLoad(new Integer(timeout));
            }
            //Thread.sleep(new Integer(timeout));
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            printMessage("**** Failed to Execute Java Script " + timer.getPrintTime() + " Element id=" + this.id
                    + " " + getExceptionMessage(e));
        }

        return false;
    }

    public void executeElement() {

    }

    public void printMessage(String msg) {
        WmLog.printMessage(msg);
        if (this.isMultiThreaded) {
            try {
                if (!this.isLogClosed) {
                    this.logfile.append("\n" + msg);
                    this.logfile.flush();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public void printCommand(String msg) {

        if (this.isMultiThreaded) {
            try {
                if (!this.isLogClosed) {
                    this.commandlogfile.append("\n" + msg);
                    this.commandlogfile.flush();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public void setImpilicitTimeInMiliSec(int timeout) throws TestMaxException {
        if (this.getDriver() == null) {
            throw new TestMaxException(
                    "ERROR : Can not reset DRIVER for browser= " + this.threadIndex + " which is NULL!");
        }
        try {
            this.getDriver().manage().timeouts().implicitlyWait(timeout + 10000, TimeUnit.MILLISECONDS);

        } catch (Exception e) {
            String msg = "Dataset:" + this.threadIndex + " ERROR: BROWSER DIED! TRYING to reset time!"
                    + getExceptionMessage(e);
            this.printMessage(msg);
            int counter = 0;
            //Try 10 times otherwise throw Exception
            while (counter < 5) {
                try {
                    Thread.sleep(500);
                    msg = "Dataset:" + this.threadIndex + " TRYING DRIVER RESET TRIAL=" + counter
                            + " to reset time!" + getExceptionMessage(e);
                    this.printMessage(msg);
                    //retry
                    this.getDriver().manage().timeouts().implicitlyWait(timeout + 10000, TimeUnit.MILLISECONDS);
                    return;

                } catch (InterruptedException e1) {
                    msg = "Dataset:" + this.threadIndex + " DRIVER RESET TRIAL=" + counter + " to reset time!"
                            + getExceptionMessage(e);
                    this.printMessage(msg);
                    counter++;
                    // TODO Auto-generated catch block
                    //e1.printStackTrace();
                } catch (Exception e1) {
                    //e1.printStackTrace();
                    msg = "Dataset:" + this.threadIndex + " DRIVER RESET TRIAL EXCEPTION=" + counter
                            + " to reset time!" + getExceptionMessage(e);
                    this.printMessage(msg);
                    counter++;
                }
            }

        }
        return;

    }

    protected void invokeMoves(List<String> moves) {
        for (String move : moves) {
            String havingattribute = move.split("@@")[1];
            String tag = move.split("@@")[0];
            String elmId = this.executeMove(tag, havingattribute);
            this.resetElementId(elmId);
        }
    }

    protected String executeMove(String tag, String havintattribute) {
        WebElement elm = null;
        String id = "testmax_elm_move_id";
        HashMap<String, String> attribs = getAttributesList(tag, havintattribute);

        String txtcond = "elms[i].innerHTML && elms[i].innerHTML.indexOf(\"@text\")>=0 "
                + "||elms[i].innerText &&elms[i].innerText.indexOf(\"@text\")>=0"
                + "||elms[i].textContent &&elms[i].textContent.indexOf(\"@text\")>=0";
        String ifer = "";
        String setid = "";
        //if(this.operation.equalsIgnoreCase("write")||this.operation.equalsIgnoreCase("click")){
        setid = "\n\t\t\tif(elms[i].offsetWidth > 0 || elms[i].offsetHeight > 0)" + "\n\t\t\t\t{ "
                + "\n\t\t\t\t\telms[i].setAttribute('id','" + id + "');" + "\n\t\t\t\t\tbreak;" + "\n\t\t\t\t}";
        /* }else{
            setid= "\n\t\t\t"+
               "\n\t\t\t\telms[i].setAttribute('id','"+id+"');"+
               "\n\t\t\t\tbreak;"+
               "\n\t\t\t";
         }*/
        String script = "\n\tvar elms=null;" + "\n\t elms=document.querySelectorAll('" + tag + "'); "
                + "\n\tif(elms &&elms.length==1)\n\t\t\t\t{ " + "\n\t\t\t\t\telms[0].setAttribute('id','" + id
                + "');" +
                //"\n\t\t\t\t\t return;"+
                "\n\t\t\t\t}" + "\n\t\tfor (var i=0; i < elms.length; i++){" + "\n\t\t\tif( @cond)" + "\n\t\t\t\t{ "
                + setid + "\n\t\t\t\t}" + "\n\t\t}";

        String othercond = "";
        String textcondfinal = "";
        String amph = "";
        for (String key : attribs.keySet()) {
            key = key.trim();
            if (key.equalsIgnoreCase("id") && !this.isEmptyValue(attribs.get("id"))) {
                id = attribs.get("id");
                //elm=this.getDriver().findElement(By.id(id));
                elm = this.waitForElement(this.getDriver().findElement(By.id(id)), new Integer(500));
                break;
            }
            if (key.equalsIgnoreCase("text") && attribs.get(key) != null) {
                txtcond = txtcond.replaceAll("@text", attribs.get(key));
                if (attribs.size() > 1) {
                    textcondfinal = "(" + txtcond + ")";
                } else {
                    textcondfinal = txtcond;
                }
            }
            if ((key.equalsIgnoreCase("href") || key.equalsIgnoreCase("img")) && attribs.get(key) != null) {

                othercond += "&& elms[i].getAttribute('" + key.trim() + "').indexOf('" + attribs.get(key).trim()
                        + "')>=0";
            } else if (!key.equalsIgnoreCase("text") && !key.equalsIgnoreCase("xpath")
                    && attribs.get(key) != null) {

                othercond += "&& elms[i].getAttribute('" + key.trim() + "')=='" + attribs.get(key).trim() + "'";
            }
        }
        if (elm == null) {

            try {
                textcondfinal = textcondfinal
                        + (this.isEmptyValue(textcondfinal) ? othercond.substring(2) : othercond);
                script = script.replace("@cond", textcondfinal);

                Thread.sleep(new Integer(500));
                ((JavascriptExecutor) this.getDriver()).executeScript(script);
                try {
                    elm = this.waitForElement(this.getDriver().findElement(By.id(id)), new Integer(timeout));
                } catch (Exception e) {
                    this.printMessage("####### Exception thrown while accesing Elementat getElementId() : "
                            + getExceptionMessage(e) + " Script=" + script);
                    return id;
                }

            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                printMessage("**** Executed Java Script With EXCEPTION " + timer.getPrintTime() + " "
                        + getExceptionMessage(e) + " Script=" + script);
                return id;
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                printMessage("**** Executed Java Script With EXCEPTION " + timer.getPrintTime() + " "
                        + getExceptionMessage(e) + " Script=" + script);
                return id;
            } catch (WebDriverException e) {
                printMessage("**** Executed Java Script With EXCEPTION " + timer.getPrintTime() + " "
                        + getExceptionMessage(e) + " Script=" + script);
                return id;
            } catch (Exception e) {
                this.printMessage("####### Exception thrown while accesing Elementat getElementId() : "
                        + getExceptionMessage(e) + " Script=" + script);
                return id;
            }
            printMessage("**** Executed Java Script " + timer.getPrintTime() + " Script=" + script);
        }
        if (elm != null) {
            try {
                new Actions(this.getDriver()).moveToElement(elm).click().build().perform();

            } catch (Exception e) {
                this.printMessage("####### Exception thrown while click and movemouse : " + getExceptionMessage(e));
                return id;
            }

        }
        return id;
    }

    protected String getElementId() {
        String id = "testmax_elm_lookup_id";
        HashMap<String, String> attribs = getAttributesList();

        String txtcond = "elms[i].innerHTML && elms[i].innerHTML.indexOf(\"@text\")>=0 "
                + "||elms[i].innerText &&elms[i].innerText.indexOf(\"@text\")>=0"
                + "||elms[i].textContent &&elms[i].textContent.indexOf(\"@text\")>=0";
        String ifer = "";
        String setid = "";
        if (this.operation.equalsIgnoreCase("write") || this.operation.equalsIgnoreCase("click")) {
            setid = "\n\t\t\t\tif(elms[i].offsetWidth > 0 || elms[i].offsetHeight > 0)" + "\n\t\t\t\t\t{ "
                    + "\n\t\t\t\t\t\telms[i].setAttribute('id','" + id + "');" + "\n\t\t\t\t\t\tbreak;"
                    + "\n\t\t\t\t\t}";
        } else if (this.operation.equalsIgnoreCase("closepopup")) {
            setid = "\n\t\t\t\tif(elms[i].offsetWidth > 0 || elms[i].offsetHeight > 0)" + "\n\t\t\t\t\t{ "
                    + "\n\t\t\t\t\t\telms[i].click();" + "\n\t\t\t\t\t\tbreak;" + "\n\t\t\t\t\t}";
        } else {
            setid = "\n\t\t\t" + "\n\t\t\t\telms[i].setAttribute('id','" + id + "');" + "\n\t\t\t\tbreak;"
                    + "\n\t\t\t";
        }
        String script = "\n\tvar elms=null;" + "\n\telms=document.querySelectorAll('" + this.tagName + "'); "
                + "\n\t\t\tif(elms &&elms.length==1)\n\t\t\t\t{ " + "\n\t\t\t\t\telms[0].setAttribute('id','" + id
                + "');" +
                //"\n\t\t\t\t\t return;"+
                "\n\t\t\t\t}";
        String cond = "\n\t\tfor (var i=0; i < elms.length; i++){" + "\n\t\t\tif( @cond)" + "\n\t\t\t\t{ " + setid
                + "\n\t\t\t\t}" + "\n\t\t}";

        if (this.isEmptyValue(this.tagName) && !this.isEmptyValue(this.havingTag)) {
            this.tagName = this.havingTag;
        }

        String othercond = "";
        String textcondfinal = "";
        String amph = "";
        for (String key : attribs.keySet()) {
            key = key.trim();
            if (key.equalsIgnoreCase("id") && !this.isEmptyValue(attribs.get("id"))
                    && !this.operation.equalsIgnoreCase("closepopup")) {
                return attribs.get("id");
            }

            if (key.equalsIgnoreCase("text") && attribs.get(key) != null) {
                txtcond = txtcond.replaceAll("@text", attribs.get(key));
                if (attribs.size() > 1) {
                    textcondfinal = "(" + txtcond + ")";
                } else {
                    textcondfinal = txtcond;
                }
            }
            if (!key.equalsIgnoreCase("text") && !key.equalsIgnoreCase("xpath") && attribs.get(key) != null) {
                if (this.isEmptyValue(othercond)) {
                    othercond = "&& (";
                } else if (!this.isEmptyValue(attribs.get(key).trim()) && textcondfinal.isEmpty()) {
                    othercond += " && ";
                } else if (!this.isEmptyValue(attribs.get(key).trim())) {
                    othercond += " || ";
                }
            }
            if ((key.equalsIgnoreCase("href") || key.equalsIgnoreCase("img")) && attribs.get(key) != null) {

                othercond += "elms[i].getAttribute('" + key.trim() + "') && elms[i].getAttribute('" + key.trim()
                        + "').indexOf('" + attribs.get(key).trim() + "')>=0";
            } else if (!key.equalsIgnoreCase("text") && !key.equalsIgnoreCase("xpath")
                    && attribs.get(key) != null) {

                othercond += "elms[i].getAttribute('" + key.trim() + "') && elms[i].getAttribute('" + key.trim()
                        + "').indexOf('" + attribs.get(key).trim() + "')>=0";
            }
        }
        if (!this.isEmptyValue(othercond) && othercond.length() > 5) {
            othercond += ")";
        }
        textcondfinal = textcondfinal
                + (this.isEmptyValue(textcondfinal) && !this.isEmptyValue(othercond) ? othercond.substring(3)
                        : (othercond.length() > 6 ? othercond : ""));
        script = script + (!this.isEmptyValue(textcondfinal) ? cond.replace("@cond", textcondfinal) : "");

        try {

            Thread.sleep(new Integer(1000));

            try {
                if (this.operation.equalsIgnoreCase("closepopup")) {
                    this.popupscripts.put(this.tagdesc, script);
                    return null;
                }

                ((JavascriptExecutor) this.getDriver()).executeScript(script);
                //this.waitForElement(this.getDriver().findElement(By.id(id)), new Integer(timeout));
                printMessage("**** Executed Java Script " + timer.getPrintTime() + "\n Script=" + script);
            } catch (Exception e) {
                this.printMessage("####### Exception thrown while executing java script at getElementId() : "
                        + getExceptionMessage(e) + "\n Script=" + script);
                return null;
            }

        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            printMessage("**** Executed Java Script With EXCEPTION " + timer.getPrintTime() + " "
                    + getExceptionMessage(e) + " \n Script=" + script);
            return null;
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            printMessage("**** Executed Java Script With EXCEPTION " + timer.getPrintTime() + " "
                    + getExceptionMessage(e) + "\n Script=" + script);
            return null;
        } catch (WebDriverException e) {
            printMessage("**** Executed Java Script With EXCEPTION " + timer.getPrintTime() + " "
                    + getExceptionMessage(e) + "\n Script=" + script);
            return null;
        }

        return id;
    }

    protected void resetElementId(String elmId) {
        String resetId = null;
        try {
            resetId = "document.getElementById('" + elmId + "').setAttribute('id',' ');";

            ((JavascriptExecutor) this.getDriver()).executeScript(resetId);

        } catch (WebDriverException e) {
            //printMessage("**** Executed Java Script With EXCEPTION to reset id="+elmId+ " "+timer.getPrintTime()+" "+getExceptionMessage(e)+" Script="+resetId);
        }

    }

    public WebDriver getDriver() {
        synchronized (this.driver) {
            this.driver = driverList.get(this.threadIndex);
        }
        if (this.driver == null) {
            return null;
        }
        try {
            this.isPopupFound = false;
            boolean child = false;
            for (String handle : driver.getWindowHandles()) {
                try {
                    driver.switchTo().window(handle);
                    child = true;

                    if (!this.isEmptyValue(window) && !this.isEmptyValue(handle)
                            && window.equalsIgnoreCase(handle)) {
                        //this.printMessage("#### Located Popup window with handle="+handle);
                        isPopupFound = true;
                        break;
                    }
                } catch (Exception e) {
                    this.printMessage(
                            "WARNING: Failed to locate Popup window with exception! " + getExceptionMessage(e));
                    child = false;
                }
            }
            if (!child) {
                driver.switchTo().defaultContent();
            }
            if (this.iframe != null && !this.iframe.isEmpty()) {
                String[] iframes = this.iframe.split("#");
                boolean hasException = false;
                for (String v_iframe : iframes) {
                    try {
                        int frameIdx = Integer.parseInt(v_iframe);
                        if (frameIdx >= 0) {
                            v_iframe = "testmax_frame_" + frameIdx;
                            String script = "var elms=document.querySelectorAll('iframe'); " + "\nelms[" + frameIdx
                                    + "].setAttribute('id','" + v_iframe + "');";
                            this.executeScript(script);
                        }
                    } catch (NumberFormatException e) {

                    }
                    hasException = false;
                    try {
                        WebElement v_frame = driver.findElement(By.id(v_iframe));
                        driver.switchTo().frame(v_frame);
                        isIframe = true;
                        break;
                    } catch (Exception e) {
                        hasException = true;
                    }
                }
                if (hasException) {
                    driver.switchTo().defaultContent();
                }

                return this.driver;
            }

        } catch (Exception e) {
            String msg = "########### DRIVER OBJECT EXCEPTION, SWITCHING WINDOW ************************";
            this.printMessage(msg);
            return null;
            //return this.driver;
        }
        return this.driver;
    }

    public WebElement waitForElement(WebElement elementToWaitFor, Integer waitTimeInMili) {
        WebElement elm = null;
        WebDriverWait wait = null;
        if (waitTimeInMili == null) {
            waitTimeInMili = 10000;
        }
        try {
            this.setImpilicitTimeInMiliSec(new Integer(waitTimeInMili));

            wait = new WebDriverWait(this.getDriver(), waitTimeInMili / 1000);
            elm = wait.until(ExpectedConditions.visibilityOf(elementToWaitFor));

        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TestMaxException e) {
            // TODO Auto-generated catch block
            //wait = new WebDriverWait(this.getDriver(), waitTimeInMili/1000);
            // elm= wait.until(ExpectedConditions.);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            //wait = new WebDriverWait(this.getDriver(), waitTimeInMili/1000);
            // elm= wait.until(ExpectedConditions.presenceOfElementLocated(by));
        }

        return elm;
    }

    protected boolean waitToPageLoad(final int timeout) {
        final PrintTime timer = new PrintTime();
        int counter = 0;
        WebElement element = null;
        int addTimeOut = 5000;
        if (isAlertPresent()) {
            this.driver.switchTo().alert().accept();
        }
        if (this.isIE) {
            addTimeOut = addTimeOut + new Integer(ConfigLoader.getConfig("SELENIUM_IE_EXTRA_TIME") == null ? "1500"
                    : ConfigLoader.getConfig("SELENIUM_IE_EXTRA_TIME"));
        }
        final int timeoutmax = timeout + addTimeOut;
        try {

            //Define an ExpectedCondition 
            ExpectedCondition<WebElement> expectedCondition = new ExpectedCondition<WebElement>() {

                public WebElement apply(WebDriver d) {

                    WebElement element1 = null;
                    boolean isTraceAdded = false;
                    int timeElapsed = 0;
                    try {
                        while (!isTraceAdded) {
                            isTraceAdded = addAttributeToElement();
                            timeElapsed = timeElapsed + 200;
                            Thread.sleep(200);
                        }

                    } catch (TestMaxException t) {
                        // TODO Auto-generated catch block
                        t.printStackTrace();
                        return null;

                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (isTraceAdded) {
                        try {
                            setImpilicitTimeInMiliSec(timeoutmax);

                            printMessage("**** LOCATING PAGE LOAD TRACE ELEMENT:" + timer.getPrintTime()
                                    + " with Id=" + controlIdentifier);
                            element1 = d.findElement(By.id(trackId));
                            waitForElement(element1, null);

                            if (element1 != null) {
                                printMessage("**** PAGE LOAD TRACE ELEMENT LOCATED :" + timer.getPrintTime()
                                        + " Status=" + element1.getAttribute("status") + " with Id="
                                        + controlIdentifier);
                                return element1.getAttribute("status").equalsIgnoreCase("complete") ? element1
                                        : null;
                            }
                        } catch (TestMaxException t) {
                            // TODO Auto-generated catch block
                            t.printStackTrace();
                            return element1;

                        }
                    }

                    return null;
                }

            };

            //Wait for page load
            /* while(element==null && counter<3){
                counter++;
                this.printMessage("******WAITING FOR PAGE LOAD TRIAL="+counter+" Element Trace Time:"+timer.getPrintTime()+" with Id="+this.controlIdentifier);    
                
             }*/
            setImpilicitTimeInMiliSec(timeout);
            this.printMessage(
                    "####### Element Trace Time:" + timer.getPrintTime() + " with Id=" + this.controlIdentifier);

            if (element == null) {
                throw new TestMaxException("$$$$$ FAILED to add trace element! Element Trace Time:"
                        + timer.getPrintTime() + " with Id=" + this.controlIdentifier);
            }

            //True or false, did we return it? 
        } catch (Exception e) {
            //this.printMessage("####### FAILED Element Trace Time:"+timer.getPrintTime()+" with Id="+this.controlIdentifier+" :"+addMessage());

            return (element != null);
        }
        return (element != null);

    }

    /*
     *  var testMaxElm = document.getElementById('"+byVal+"'); var testMaxNewElm = document.createElement('<div id=TestMaxAutomation></div>');testMaxElm.appendChild(testMaxNewElm);
     */
    private boolean addAttributeToElement() throws NumberFormatException, TestMaxException {
        PrintTime timer = new PrintTime();
        //String [] trackingIds=ConfigLoader.getConfig("SELENIUM_TRACKING_ELEMENT_IDS").split(";");
        //String [] trackingIds={"SeleniumTrackId"};
        //for(String v_trackId:trackingIds){
        setImpilicitTimeInMiliSec(new Integer(timeout));
        try {
            this.trackId = "TestMax_" + new Random().nextInt();
            ((JavascriptExecutor) this.getDriver())
                    .executeScript("var testMaxElm= document.getElementsByTagName('body')[0]; "
                            + " var state=document.readyState; " + " var testMaxNewElm = document.getElementById('"
                            + this.trackId + "');  " + " if(testMaxNewElm==null) {  "
                            + " testMaxNewElm = document.createElement('div'); testMaxNewElm.setAttribute(\"id\",\""
                            + this.trackId + "\"); "
                            + "testMaxNewElm.setAttribute(\"status\",state);  testMaxElm.appendChild(testMaxNewElm);}else{testMaxNewElm.setAttribute(\"status\",state);}");
            printMessage("**** Added Trace" + timer.getPrintTime() + " DIV id=" + this.trackId);

            return true;
        } catch (Exception e) {
            String msg = "**** Failed to Add Trace " + timer.getPrintTime() + " DIV id=" + this.trackId
                    + addMessage();
            printMessage(msg);
            try {
                //if(this.operation.equalsIgnoreCase("acceptalert")){

                if (this.driver.switchTo().alert() != null) {
                    this.driver.switchTo().alert().accept();
                    msg = "**** ALERT Traced " + timer.getPrintTime() + " DIV id=" + this.trackId + " Message: "
                            + addMessage();
                } else {
                    throw new TestMaxException(msg);
                }

            } catch (Exception a) {
                throw new TestMaxException(msg);
            }

        }

        //if fails in above     
        try {
            if (this.id != null && !this.id.isEmpty()) {
                this.trackId = "TestMax_" + id;
                ((JavascriptExecutor) this.getDriver())
                        .executeScript("var state=document.readyState; var testMaxElm = document.getElementById('"
                                + this.id + "'); "
                                + " var testMaxNewElm = document.createElement('div'); testMaxNewElm.setAttribute(\"id\",\""
                                + this.trackId + "\"); "
                                + "testMaxNewElm.setAttribute(\"status\",state);  testMaxElm.appendChild(testMaxNewElm);");
                printMessage("**** Added Trace " + timer.getPrintTime() + " DIV id=" + this.trackId
                        + " under Target Element DIV Element Identifier=" + this.id);

                return true;
            }

        } catch (Exception e) {
            String msg = "****Dataset:" + this.threadIndex + " Failed to Add Trace " + timer.getPrintTime()
                    + " DIV id=" + this.trackId + " under Element ID=" + id + " Message: " + addMessage();
            printMessage(msg);
            try {
                //if(this.operation.equalsIgnoreCase("acceptalert")){
                if (this.driver.switchTo().alert() != null) {
                    this.driver.switchTo().alert().accept();
                    msg = "**** ALERT Traced " + timer.getPrintTime() + " DIV id=" + this.trackId
                            + " under Element ID=" + id + " Message: " + addMessage();
                } else {
                    throw new TestMaxException(msg);
                }
            } catch (Exception a) {
                throw new TestMaxException(msg);
            }
        }

        return false;
    }

    public boolean isAlertPresent() {
        try {
            this.driver.switchTo().alert();
            return true;
        } // try 
        catch (NoAlertPresentException Ex) {
            return false;
        } // catch 
    }

    protected String addMessage() {
        return (timer.getPrintTime());
        //return (timer.getPrintTime()+">> Control="+this.controlIdentifier +">> Executing Tag="+this.targetTag.asXML());
    }

    public boolean isEmptyValue(String val) {
        if (val == null || val.isEmpty()) {
            return true;
        }
        return false;
    }

    protected String getExceptionMessage(Exception e) {
        String emsg = e.getMessage();
        if (emsg.length() > 200) {
            return emsg.substring(0, 200);

        } else
            return emsg;
    }

}