Example usage for org.openqa.selenium OutputType BASE64

List of usage examples for org.openqa.selenium OutputType BASE64

Introduction

In this page you can find the example usage for org.openqa.selenium OutputType BASE64.

Prototype

OutputType BASE64

To view the source code for org.openqa.selenium OutputType BASE64.

Click Source Link

Document

Obtain the screenshot as base64 data.

Usage

From source file:Util.java

License:Apache License

/**
 * // Takes a screen shot if the driver's capabilities include Screen Shots
 * @param driver        The Web Driver instance
 * @param outputType    Either FILE or Base64
 * @param folder        The folder for images
 * @param filename      The base file name (sans time stamp)
 * @return              Error string starting with ERROR: if failed to create file or the file name that was created
 *//*from   w w w .j  a va2 s. c om*/
public static String takeScreenImage(WebDriver driver, String folder, String fileName) {
    String result = "";
    WebDriver theDriver = Driver.getDriver();

    if (!(theDriver instanceof WebDriver)) {
        return "ERROR: No Web Driver found at this step!";
    }

    if (!((HasCapabilities) theDriver).getCapabilities().is(CapabilityType.TAKES_SCREENSHOT)) {
        return "ERROR: Driver " + Util.sq(theDriver.toString())
                + " has no TAKES_SCREENSHOT capabilities.  Screen shot not taken";
    }

    String imagesFolder = (isBlank(folder)) ? DDTTestRunner.getReporter().sessionImagesFolderName() : folder;

    try {
        File testTempDir = new File(DDTSettings.asValidOSPath(imagesFolder, true));
        if (testTempDir.exists()) {
            if (!testTempDir.isDirectory()) {
                return "ERROR: Image path exists but is not a directory";
            }
        } else {
            testTempDir.mkdirs();
        }
    } catch (Exception e) {
        return "ERROR: File operation (mkdir) failed. " + e.getCause();
    }

    String actualFileName = fileName + " - " + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date())
            + ".png";

    // create screenshot using a casted driver
    TakesScreenshot snapper = (TakesScreenshot) theDriver;

    if (DDTSettings.Settings().isLocal()) {
        File tempImageFile = snapper.getScreenshotAs(OutputType.FILE);
        if (tempImageFile.length() < (1L)) {
            return "ERROR: Failed to take screen shot on remote driver";
        }

        File tmpFile = new File(imagesFolder, DDTSettings.asValidOSPath(actualFileName, true)); // testTempImage
        // move screenshot to our local store
        try {
            FileUtils.moveFile(tempImageFile, tmpFile);
        } catch (Exception e) {
            return "ERROR: Failed to move tmp file to image file. " + Util.sq(tmpFile.getAbsolutePath()) + " "
                    + e.getCause().toString();
        }

        if (tmpFile.length() < 1L) {
            return "ERROR: Failed to move tmp file to image file. " + Util.sq(tmpFile.getAbsolutePath());
        }

        result = tmpFile.getAbsolutePath();
    } else {
        // Create Base64 screen shot file on the remote driver and store it locally
        String tempImageFile = snapper.getScreenshotAs(OutputType.BASE64);
        if (tempImageFile.length() < (1L)) {
            return "ERROR: Failed to take screen shot on remote driver";
        }

        Base64 decoder = new Base64();
        byte[] imgBytes = (byte[]) decoder.decode(tempImageFile);

        File tmpFile = new File(imagesFolder, DDTSettings.asValidOSPath(actualFileName, true));

        FileOutputStream osf = null;
        try {
            osf = new FileOutputStream(tmpFile);
            osf.write(imgBytes);
            osf.flush();
        } catch (Exception e) {
            return "ERROR: Failed to create File Output Stream " + e.getCause();
        }

        if (tmpFile.length() < 1L) {
            return "ERROR: File created from  File Output Stream is empty!";
        }

        result = tmpFile.getAbsolutePath();
    }

    return result;
}

From source file:com.elastica.driver.ScreenshotUtil.java

License:Apache License

public static String captureEntirePageScreenshotToString(final WebDriver driver, final String arg0) {
    if (driver == null) {
        return "";
    }//from   ww w .j av  a 2s.c  o m

    try {

        // Don't capture snapshot for htmlunit
        if (WebUIDriver.getWebUXDriver().getBrowser().equalsIgnoreCase(BrowserType.HtmlUnit.getBrowserType())) {
            return null;
        }

        // Opera has bug after upgrade selenium
        // 2.33.0,https://code.google.com/p/selenium/issues/detail?id=847
        if (WebUIDriver.getWebUXDriver().getBrowser().equalsIgnoreCase(BrowserType.Opera.getBrowserType())) {
            return null;
        }

        TakesScreenshot screenShot = (TakesScreenshot) driver;
        return screenShot.getScreenshotAs(OutputType.BASE64);
    } catch (Exception ex) {

        // Ignore all exceptions
        ex.printStackTrace();
    }

    return "";
}

From source file:com.ggasoftware.uitest.utils.ScreenShotMaker.java

License:Open Source License

/**
 * create screenshot on remote machine//from  w  ww. j  a va  2 s  .  com
 *
 * @param id - name output png file
 * @return full path
 */
public static String takeScreenshotRemote(String id) {
    String sId = id;
    String base64Screenshot;
    if (hasTake) {
        if (isDirectoryCorrect()) {
            String name = String.format("%s.png",
                    DateUtil.now(new SimpleDateFormat("HH_mm_ss-sss").toPattern()));
            try {
                TakesScreenshot tsDriver;
                tsDriver = (TakesScreenshot) WebDriverWrapper.getDriver();
                base64Screenshot = tsDriver.getScreenshotAs(OutputType.BASE64);

                byte[] decodedScreenshot = Base64.decodeBase64(base64Screenshot.getBytes());
                File file = new File(ScreenShotMaker.path + name);
                try (FileOutputStream fos = new FileOutputStream(file)) {
                    fos.write(decodedScreenshot);
                }
                if (TestBaseWebDriver.allure) {
                    saveScreenshot(decodedScreenshot);
                }
                if (TestBaseWebDriver.reportportal) {
                    ReporterNGExt.log4j(new ReportPortalMessage(file, id));
                }
            } catch (WebDriverException | IOException e) {
                sId += String.format("  [%s when making screenshot(webdriver: %s)]", e.toString(),
                        WebDriverWrapper.getDriver());
                ReporterNGExt.log4jError(String.format("%s when making screenshot(webdriver: %s; file: %s%s) ",
                        e.toString(), WebDriverWrapper.getDriver(), ScreenShotMaker.path, name));
            }
            return dir + name + "|" + sId;
        }
        ReporterNGExt.log4jError(String.format("Incorrect directory screenshot directory: %s", path));
        return String.format("Incorrect directory screenshot directory: %s", path);
    } else {
        return id;
    }
}

From source file:com.google.android.testing.nativedriver.server.AndroidNativeDriver.java

License:Apache License

@Override
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
    if (target != OutputType.BASE64)
        throw new WebDriverException("You must use getScreenShotAsBase64");

    //Credit: This screenshot stuff is 99% from the people at
    //http://stackoverflow.com/questions/2661536/how-to-programatically-take-a-screenshot-on-android
    //http://stackoverflow.com/questions/2339429/android-view-getdrawingcache-returns-null-only-null
    Runnable myrunner = new Runnable() {
        @Override/*from   w  w w .j a va2  s  .co  m*/
        public void run() {
            Bitmap bitmap;
            View rootview = context.getActivities().current().getWindow().getDecorView().getRootView();
            rootview.setDrawingCacheEnabled(true);
            rootview.buildDrawingCache(true);
            rootview.layout(0, 0, rootview.getWidth(), rootview.getHeight());
            bitmap = Bitmap.createBitmap(rootview.getDrawingCache());
            rootview.buildDrawingCache(false);
            rootview.setDrawingCacheEnabled(false);
            try {
                baostream = new ByteArrayOutputStream(bitmap.getRowBytes() * bitmap.getHeight());
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baostream);
            } catch (Exception e) {
                Log.i("appdriver", e.toString());
                throw new WebDriverException(e.toString());
            }
            try {
                synchronized (this) {
                    this.notify();
                }
            } catch (Exception e) {
                Log.i("appdriver", e.toString());
                throw new WebDriverException(e.toString());
            }
        }
    };
    context.getActivities().current().runOnUiThread(myrunner);
    try {
        synchronized (myrunner) {
            myrunner.wait();
        }
    } catch (Exception e) {
        Log.i("appdriver", e.toString());
        throw new WebDriverException(e.toString());
    }
    try {
        byte[] imagebytes = baostream.toByteArray();
        baostream.close();
        return (X) Base64.encodeToString(imagebytes, 0);
    } catch (Exception e) {
        Log.i("appdriver", e.toString());
        throw new WebDriverException(e.toString());
    }
}

From source file:com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebDriver.java

License:Open Source License

@Override
public String takeScreenShot() {
    return getScreenshotAs(OutputType.BASE64);
}

From source file:com.seleniumtests.driver.screenshots.ScreenshotUtil.java

License:Apache License

/**
 * Capture current page (either web or app page)
 * This is a wrapper around the selenium screenshot capability
 * @return//from ww w .  ja  v  a 2s .c  om
 */
public BufferedImage capturePage(int cropTop, int cropBottom) {
    if (driver == null) {
        return null;
    }

    try {
        // Don't capture snapshot for htmlunit
        if (SeleniumTestsContextManager.getThreadContext().getBrowser() == BrowserType.HTMLUNIT) {
            return null;
        }

        TakesScreenshot screenShot = (TakesScreenshot) driver;

        // TEST_MOBILE
        //                ((AndroidDriver<WebElement>)((CustomEventFiringWebDriver)driver).getWebDriver()).getContextHandles();
        //                ((AndroidDriver<WebElement>)((CustomEventFiringWebDriver)driver).getWebDriver()).context("CHROMIUM");
        // TEST_MOBILE

        // android does not support screenshot from webview context, switch temporarly to native_app context to take screenshot
        if (SeleniumTestsContextManager.getThreadContext().getBrowser() == BrowserType.BROWSER) {
            ((AndroidDriver<WebElement>) ((CustomEventFiringWebDriver) driver).getWebDriver())
                    .context("NATIVE_APP");
        }

        String screenshotB64 = screenShot.getScreenshotAs(OutputType.BASE64);
        if (SeleniumTestsContextManager.getThreadContext().getBrowser() == BrowserType.BROWSER) {
            ((AndroidDriver<WebElement>) ((CustomEventFiringWebDriver) driver).getWebDriver())
                    .context("WEBVIEW");
        }

        BufferedImage capturedImage = ImageProcessor.loadFromB64String(screenshotB64);

        // crop capture by removing headers
        if (cropTop >= 0 && cropBottom >= 0) {

            // in case driver already capture the whole content, do not crop anything as cropping is used to remove static headers when scrolling
            Dimension contentDimension = ((CustomEventFiringWebDriver) driver).getContentDimension();
            if (capturedImage.getWidth() == contentDimension.width
                    && capturedImage.getHeight() == contentDimension.height) {
                return capturedImage;
            }

            Dimension dimensions = ((CustomEventFiringWebDriver) driver).getViewPortDimensionWithoutScrollbar();
            capturedImage = ImageProcessor.cropImage(capturedImage, 0, cropTop, dimensions.getWidth(),
                    dimensions.getHeight() - cropTop - cropBottom);
        }

        return capturedImage;
    } catch (Exception ex) {
        // Ignore all exceptions
        logger.error("capturePageScreenshotToString: ", ex);
    }

    return null;
}

From source file:com.seleniumtests.driver.ScreenshotUtil.java

License:Apache License

public static String captureEntirePageScreenshotToString(final WebDriver driver, final String arg0) {
    if (driver == null) {
        return "";
    }//  ww w  .java2  s. c  om

    try {

        // Don't capture snapshot for htmlunit
        if (WebUIDriver.getWebUIDriver().getBrowser().equalsIgnoreCase(BrowserType.HtmlUnit.getBrowserType())) {
            return null;
        }

        if (WebUIDriver.getWebUIDriver().getBrowser().equalsIgnoreCase(BrowserType.Android.getBrowserType())) {
            return null;
        }

        TakesScreenshot screenShot = (TakesScreenshot) driver;
        return screenShot.getScreenshotAs(OutputType.BASE64);
    } catch (Exception ex) {

        // Ignore all exceptions
        ex.printStackTrace();
    }

    return "";
}

From source file:com.smash.revolance.ui.model.helper.BotHelper.java

License:Open Source License

public static String takeScreenshot(Bot bot) throws Exception {
    try {//from   w  w  w  .  ja  v a  2 s .  c  o m
        return ImageHelper.BASE64_IMAGE_PNG
                + ((TakesScreenshot) bot.getBrowser()).getScreenshotAs(OutputType.BASE64);
    } catch (Exception e) {
        System.err.println(e);
        throw e;
    }
}

From source file:com.thoughtworks.selenium.webdriven.commands.CaptureScreenshotToString.java

License:Apache License

@Override
protected String handleSeleneseCommand(WebDriver driver, String locator, String value) {
    if (driver instanceof TakesScreenshot) {
        TakesScreenshot tsDriver = (TakesScreenshot) driver;
        return tsDriver.getScreenshotAs(OutputType.BASE64);
    }/*  w  w w  .  ja  v  a2 s  .  co m*/
    throw new UnsupportedOperationException("WebDriver does not implement TakeScreenshot");
}

From source file:com.twiceagain.mywebdriver.driver.web.Drivers.java

License:Open Source License

/**
 * Takes a (full view) Base64 screenshoot from the provided webdriver.
 *
 * @param wd - the driver to shoot.// w  ww.  ja  v a2  s .  c  om
 * @return Base64 string. You can use it directly to display inline images.
 */
public static String screenshot2B64(WebDriver wd) {
    return ((TakesScreenshot) wd).getScreenshotAs(OutputType.BASE64);
}