Example usage for org.aspectj.lang ProceedingJoinPoint getArgs

List of usage examples for org.aspectj.lang ProceedingJoinPoint getArgs

Introduction

In this page you can find the example usage for org.aspectj.lang ProceedingJoinPoint getArgs.

Prototype

Object[] getArgs();

Source Link

Usage

From source file:com.seleniumtests.core.aspects.LogAction.java

License:Apache License

/**
 * exclude driver creation from the time of the current step
 * @param joinPoint/*from  w  ww  .ja v a  2s .  c  o  m*/
 * @return
 * @throws Throwable
 */
@Around("execution(public org.openqa.selenium.WebDriver com.seleniumtests.driver.WebUIDriver.createRemoteWebDriver (..))")
public Object measureDriverCreation(ProceedingJoinPoint joinPoint) throws Throwable {
    TestStep cuurrentTestStep = TestLogging.getCurrentRootTestStep();
    long start = new Date().getTime();

    try {
        return joinPoint.proceed(joinPoint.getArgs());
    } finally {

        long duration = new Date().getTime() - start;
        if (cuurrentTestStep != null) {
            cuurrentTestStep.setDurationToExclude(duration);
        }
        TestLogging.info(String.format("driver creation took: %f secs", duration / 1000.0));
    }
}

From source file:com.seleniumtests.core.aspects.LogAction.java

License:Apache License

/**
 * Log a TestStep, inside a parent TestStep or not
 * Common method used for all test step logging
 * @return/*from   w  ww  .  ja va2  s .  c  om*/
 * @throws Throwable 
 */
private Object commonLogTestStep(ProceedingJoinPoint joinPoint, String stepNamePrefix, boolean configStep)
        throws Throwable {
    Object reply = null;
    boolean rootStep = false;
    TestStep previousParent = null;

    // step name will contain method arguments only if it's not a configuration method (as they are generic)
    TestStep currentStep = buildRootStep(joinPoint, stepNamePrefix, !configStep);

    BrowserMobProxy mobProxy = WebUIDriver.getBrowserMobProxy();
    NLWebDriver neoloadDriver = WebUIDriver.getNeoloadDriver();

    // check if any root step is already registered (a main step)
    // happens when using cucumber where a cucumber method can call an other method intercepted by this pointcut
    // ex: Given (url "www.somesite.com") calls "open(url)"
    // In this case, open becomes a child of Given
    // if rootStep is null, parent step is also null
    if (TestLogging.getCurrentRootTestStep() == null) {
        TestLogging.setCurrentRootTestStep(currentStep); // will also set parent step
        rootStep = true;

        if (mobProxy != null) {
            mobProxy.newPage(currentStep.getName());
        }
        if (neoloadDriver != null) {
            neoloadDriver.startTransaction(currentStep.getName());
        }

    } else {
        TestLogging.getParentTestStep().addStep(currentStep);
        previousParent = TestLogging.getParentTestStep();
        TestLogging.setParentTestStep(currentStep);
    }

    try {
        reply = joinPoint.proceed(joinPoint.getArgs());
    } catch (Throwable e) {
        currentStep.setFailed(true);
        currentStep.setActionException(e);
        throw e;
    } finally {
        if (rootStep) {
            TestLogging.getCurrentRootTestStep().updateDuration();
            TestLogging.logTestStep(TestLogging.getCurrentRootTestStep());

            if (neoloadDriver != null) {
                neoloadDriver.stopTransaction();
            }
        } else {
            TestLogging.setParentTestStep(previousParent);
        }
    }
    return reply;
}

From source file:com.seleniumtests.uipage.aspects.InterceptBy.java

License:Apache License

/**
 * Change the argument of the By. when it's in the mapping files
 * @param joinPoint/*from   w w  w. j a v a 2  s .  co m*/
 */
@Around("call(* org.openqa.selenium.By..* (..) )")
public Object changeArg(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();
    Object reply = null;

    if (args != null) {
        for (int i = 0; i < args.length; i++) {
            Object argument = args[i];
            if (argument != null && argument instanceof String && argument.toString().contains("map:")) {
                String[] input = ((String) argument).split(":");
                if (input[0].equals("map")) {
                    String page = getCallerName(Thread.currentThread().getStackTrace());
                    Map<String, HashMap<String, String>> config = SeleniumTestsContextManager.getThreadContext()
                            .getIdMapping();
                    if (config == null) {
                        config = new ConfigMappingReader().readConfig();
                        if (config != null && !config.isEmpty()) {
                            SeleniumTestsContextManager.getThreadContext().setIdMapping(config);
                        } else {
                            throw new ConfigurationException(
                                    "There is no mapping file correspondant to this type and version");
                        }
                    }
                    if (input[1] != null && !input[1].equals("")) {
                        if (config.get(page) != null && !config.get(page).isEmpty()) {
                            String toPass = config.get(page).get(input[1]);
                            if (toPass != null && !toPass.equals("")) {
                                args[i] = toPass;
                            } else {
                                throw new ConfigurationException(
                                        "This id is not in the mapping files for this page");
                            }
                        } else {
                            throw new ConfigurationException("This page doesn't have mapping configuration");
                        }
                    }
                }
            }

        }
    }
    reply = joinPoint.proceed(args);
    return reply;
}

From source file:com.seleniumtests.uipage.aspects.ReplayAction.java

License:Apache License

/**
 * Replay all HtmlElement actions annotated by ReplayOnError.
 * Classes which are not subclass of HtmlElement won't go there 
 * See javadoc of the annotation for details
 * @param joinPoint//from  w w w .j  a  v  a 2 s  . co m
 * @throws Throwable
 */
@Around("execution(public * com.seleniumtests.uipage.htmlelements.HtmlElement+.* (..))"
        + "&& execution(@com.seleniumtests.uipage.ReplayOnError public * * (..)) && @annotation(replay)")
public Object replayHtmlElement(ProceedingJoinPoint joinPoint, ReplayOnError replay) throws Throwable {

    Instant end = systemClock.instant()
            .plusSeconds(SeleniumTestsContextManager.getThreadContext().getReplayTimeout());
    Object reply = null;

    // update driver reference of the element
    // corrects bug of waitElementPresent which threw a SessionNotFoundError because driver reference were not
    // updated before searching element (it used the driver reference of an old test session)
    HtmlElement element = (HtmlElement) joinPoint.getTarget();
    element.setDriver(WebUIDriver.getWebDriver());
    String targetName = joinPoint.getTarget().toString();

    TestAction currentAction = null;
    String methodName = joinPoint.getSignature().getName();
    if (methodName != "getCoordinates") {
        List<String> pwdToReplace = new ArrayList<>();
        String actionName = String.format("%s on %s %s", methodName, targetName,
                LogAction.buildArgString(joinPoint, pwdToReplace, new HashMap<>()));
        currentAction = new TestAction(actionName, false, pwdToReplace);
    }

    // log action before its started. By default, it's OK. Then result may be overwritten if step fails
    // order of steps is the right one (first called is first displayed)
    if (currentAction != null && isHtmlElementDirectlyCalled(Thread.currentThread().getStackTrace())
            && TestLogging.getParentTestStep() != null) {
        TestLogging.getParentTestStep().addAction(currentAction);
    }

    boolean actionFailed = false;
    boolean ignoreFailure = false;

    try {
        while (end.isAfter(systemClock.instant())) {

            // in case we have switched to an iframe for using previous webElement, go to default content
            if (element.getDriver() != null && SeleniumTestsContextManager.isWebTest()) {
                element.getDriver().switchTo().defaultContent(); // TODO: error when clic is done, closing current window
            }

            try {
                reply = joinPoint.proceed(joinPoint.getArgs());
                WaitHelper.waitForMilliSeconds(200);
                break;
            } catch (UnhandledAlertException e) {
                throw e;
            } catch (WebDriverException e) {

                // don't prevent TimeoutException to be thrown when coming from waitForPresent
                // only check that cause is the not found element and not an other error (NoSucheSessionError for example)
                if ((e instanceof TimeoutException
                        && joinPoint.getSignature().getName().equals("waitForPresent")
                        && e.getCause() instanceof NoSuchElementException) // issue #104: do not log error when waitForPresent raises TimeoutException
                        || (e instanceof NoSuchElementException
                                && isFromExpectedConditions(Thread.currentThread().getStackTrace())) // issue #194: return immediately if the action has been performed from ExpectedConditions class
                //   This way, we let the FluentWait process to retry or re-raise the exception
                ) {
                    ignoreFailure = true;
                    throw e;
                }

                if (end.minusMillis(200).isAfter(systemClock.instant())) {
                    WaitHelper.waitForMilliSeconds(replay.replayDelayMs());
                    continue;
                } else {
                    if (e instanceof NoSuchElementException) {
                        throw new NoSuchElementException("Searched element could not be found");
                    } else if (e instanceof UnreachableBrowserException) {
                        throw new WebDriverException("Browser did not reply, it may have frozen");
                    }
                    throw e;
                }
            }

        }
        return reply;
    } catch (Throwable e) {

        if (e instanceof NoSuchElementException && joinPoint.getTarget() instanceof HtmlElement
                && (joinPoint.getSignature().getName().equals("findElements")
                        || joinPoint.getSignature().getName().equals("findHtmlElements"))) {
            return new ArrayList<WebElement>();
        } else {
            actionFailed = true && !ignoreFailure;
            throw e;
        }
    } finally {
        if (currentAction != null && isHtmlElementDirectlyCalled(Thread.currentThread().getStackTrace())
                && TestLogging.getParentTestStep() != null) {
            currentAction.setFailed(actionFailed);
        }
    }
}

From source file:com.seleniumtests.uipage.aspects.ReplayAction.java

License:Apache License

/**
 * Replay all actions annotated by ReplayOnError if the class is not a subclass of 
 * HtmlElement//  www .  j  av  a2s  . co  m
 * @param joinPoint
 * @throws Throwable
 */
@Around("!execution(public * com.seleniumtests.uipage.htmlelements.HtmlElement+.* (..))"
        + "&& execution(@com.seleniumtests.uipage.ReplayOnError public * * (..)) && @annotation(replay)")
public Object replay(ProceedingJoinPoint joinPoint, ReplayOnError replay) throws Throwable {

    int replayDelayMs = replay != null ? replay.replayDelayMs() : 100;

    Instant end = systemClock.instant()
            .plusSeconds(SeleniumTestsContextManager.getThreadContext().getReplayTimeout());
    Object reply = null;

    String targetName = joinPoint.getTarget().toString();
    TestAction currentAction = null;

    if (joinPoint.getTarget() instanceof GenericPictureElement) {
        String methodName = joinPoint.getSignature().getName();
        List<String> pwdToReplace = new ArrayList<>();
        String actionName = String.format("%s on %s %s", methodName, targetName,
                LogAction.buildArgString(joinPoint, pwdToReplace, new HashMap<>()));
        currentAction = new TestAction(actionName, false, pwdToReplace);

        // log action before its started. By default, it's OK. Then result may be overwritten if step fails
        // order of steps is the right one (first called is first displayed)
        if (isHtmlElementDirectlyCalled(Thread.currentThread().getStackTrace())
                && TestLogging.getParentTestStep() != null) {
            TestLogging.getParentTestStep().addAction(currentAction);
        }
    }

    boolean actionFailed = false;

    try {
        while (end.isAfter(systemClock.instant())) {

            try {
                reply = joinPoint.proceed(joinPoint.getArgs());
                WaitHelper.waitForMilliSeconds(200);
                break;
            } catch (Throwable e) {

                // do not replay when error comes from test writing or configuration
                if (e instanceof ScenarioException || e instanceof ConfigurationException
                        || e instanceof DatasetException) {
                    throw e;
                }

                if (end.minusMillis(200).isAfter(systemClock.instant())) {
                    WaitHelper.waitForMilliSeconds(replayDelayMs);
                    continue;
                } else {
                    throw e;
                }
            }
        }
        return reply;
    } catch (Throwable e) {
        actionFailed = true;
        throw e;
    } finally {
        if (currentAction != null && isHtmlElementDirectlyCalled(Thread.currentThread().getStackTrace())
                && TestLogging.getParentTestStep() != null) {
            currentAction.setFailed(actionFailed);

            if (joinPoint.getTarget() instanceof GenericPictureElement) {
                currentAction.setDurationToExclude(
                        ((GenericPictureElement) joinPoint.getTarget()).getActionDuration());
            }
        }
    }
}

From source file:com.seleniumtests.uipage.aspects.SeleniumNativeActions.java

License:Apache License

/**
 * Intercept any call to findElement made from a PageObject subclass and returns a HtmlElement instead of a RemoteWebElement
 * This way, every action done on this element will benefit from HtmlElement mechanism
 * @param joinPoint//w w w .j  a  v a 2s  . c  om
 * @return
 * @throws Throwable
 */
@Around("this(com.seleniumtests.uipage.PageObject) && " + // caller is a PageObject
        "(call(public * org.openqa.selenium.WebDriver+.findElement (..))" + ")")
public Object interceptFindHtmlElement(ProceedingJoinPoint joinPoint) throws Throwable {
    if (doOverride()) {
        return new HtmlElement("", (By) (joinPoint.getArgs()[0]), currentFrame);
    } else {
        return joinPoint.proceed(joinPoint.getArgs());
    }
}

From source file:com.seleniumtests.uipage.aspects.SeleniumNativeActions.java

License:Apache License

@Around("this(com.seleniumtests.uipage.PageObject) && " + // caller is a PageObject
        "(call(public * org.openqa.selenium.WebDriver+.findElements (..))" + ")")
public Object interceptFindsHtmlElement(ProceedingJoinPoint joinPoint) throws Throwable {
    if (doOverride()) {
        return new HtmlElement("", (By) (joinPoint.getArgs()[0]), currentFrame).findElements();
    } else {//from ww  w .  j a va 2 s .com
        return joinPoint.proceed(joinPoint.getArgs());
    }
}

From source file:com.seleniumtests.uipage.aspects.SeleniumNativeActions.java

License:Apache License

/**
 * Method interceptFindHtmlElement creates an HtmlElement from findElement, but does not handle frames. 
 * Here, we record all switchTo().frame(WebElement) call to create a FrameElement chain
 * @param joinPoint//from   ww w.j av a 2s. c  o m
 * @return
 * @throws Throwable
 */
@Around("this(com.seleniumtests.uipage.PageObject) && " + // caller is a PageObject
        "(call(public * org.openqa.selenium.support.ui.ExpectedConditions.frameToBeAvailableAndSwitchToIt (..))"
        + ")")
public Object recordFrameSwitch(ProceedingJoinPoint joinPoint) throws Throwable {
    if (doOverride()) {
        Object frameArg = joinPoint.getArgs()[0];
        FrameElement frameEl = getFrameElement(frameArg);

        if (frameEl == null) {
            return joinPoint.proceed(joinPoint.getArgs());
        }

        if (currentFrame == null) {
            currentFrame = frameEl;
        } else {
            frameEl.setFrameElement(currentFrame);
            currentFrame = frameEl;
        }

        return new ExpectedCondition<WebDriver>() {
            @Override
            public WebDriver apply(WebDriver driver) {
                try {
                    return driver;
                } catch (NoSuchFrameException e) {
                    return null;
                }
            }

            @Override
            public String toString() {
                return "frame to be available: " + frameArg;
            }
        };

    } else {
        return joinPoint.proceed(joinPoint.getArgs());
    }
}

From source file:com.seleniumtests.uipage.aspects.SeleniumNativeActions.java

License:Apache License

/**
 * Method interceptFindHtmlElement creates an HtmlElement from findElement, but does not handle frames. 
 * Here, we record all switchTo().frame(WebElement) call to create a FrameElement chain
 * @param joinPoint//from  w w w.  j av  a 2 s  .  co m
 * @return
 * @throws Throwable
 */
@Around("this(com.seleniumtests.uipage.PageObject) && " + // caller is a PageObject
        "(call(public * org.openqa.selenium.WebDriver.TargetLocator+.frame (..))" + ")")
public Object recordSwitchToFramCalls(ProceedingJoinPoint joinPoint) throws Throwable {
    if (doOverride()) {
        Object frameArg = joinPoint.getArgs()[0];
        FrameElement frameEl = getFrameElement(frameArg);

        if (frameEl == null) {
            return joinPoint.proceed(joinPoint.getArgs());
        }

        if (currentFrame == null) {
            currentFrame = frameEl;
        } else {
            frameEl.setFrameElement(currentFrame);
            currentFrame = frameEl;
        }
        return null;
    } else {
        return joinPoint.proceed(joinPoint.getArgs());
    }
}

From source file:com.seleniumtests.uipage.aspects.SeleniumNativeActions.java

License:Apache License

@Around("this(com.seleniumtests.uipage.PageObject) && " + // caller is a PageObject
        "(call(public * org.openqa.selenium.WebDriver.TargetLocator+.defaultContent (..))" + ")")
public Object recordSwitchDefaultContext(ProceedingJoinPoint joinPoint) throws Throwable {
    currentFrame = null;/*from w  w w .  j  a  v a 2 s.  c  o m*/
    return joinPoint.proceed(joinPoint.getArgs());
}