Example usage for org.openqa.selenium OutputType FILE

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

Introduction

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

Prototype

OutputType FILE

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

Click Source Link

Document

Obtain the screenshot into a temporary file that will be deleted once the JVM exits.

Usage

From source file:TestUtils.java

License:Open Source License

public static void saveScreenshot(WebDriver driver, String screenshotFileName) throws IOException {
    File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshot, new File(screenshotFileName));
}

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   www.j a  v  a  2s .c o m*/
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:akori.AKORI.java

public static void main(String[] args) throws IOException, InterruptedException {
    System.out.println("esto es AKORI");

    URL = "http://www.mbauchile.cl";
    PATH = "E:\\NetBeansProjects\\AKORI\\";
    NAME = "mbauchile.png";
    // Extrar DOM tree

    Document doc = Jsoup.connect(URL).timeout(0).get();

    // The Firefox driver supports javascript 
    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    System.out.println(driver.manage().window().getSize().toString());
    System.out.println(driver.manage().window().getPosition().toString());
    int xmax = driver.manage().window().getSize().width;
    int ymax = driver.manage().window().getSize().height;

    // Go to the URL page
    driver.get(URL);/* www  . j av a 2  s . c  o m*/

    File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screen, new File(PATH + NAME));

    BufferedImage img = ImageIO.read(new File(PATH + NAME));
    //Graphics2D graph = img.createGraphics();

    BufferedImage img1 = new BufferedImage(xmax, ymax, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graph1 = img.createGraphics();
    double[][] matrix = new double[ymax][xmax];
    BufferedReader in = new BufferedReader(new FileReader("et.txt"));
    String linea;
    double max = 0;
    graph1.drawImage(img, 0, 0, null);
    HashMap<String, Integer> lista = new HashMap<String, Integer>();
    int count = 0;
    for (int i = 0; (linea = in.readLine()) != null && i < 10000; ++i) {
        String[] datos = linea.split(",");
        int x = (int) Double.parseDouble(datos[0]);
        int y = (int) Double.parseDouble(datos[2]);
        long time = Double.valueOf(datos[4]).longValue();
        if (x >= xmax || y >= ymax)
            continue;
        if (time < 691215)
            continue;
        if (time > 705648)
            break;
        if (lista.containsKey(x + "," + y))
            lista.put(x + "," + y, lista.get(x + "," + y) + 1);
        else
            lista.put(x + "," + y, 1);
        ++count;
    }
    System.out.println(count);
    in.close();
    Iterator iter = lista.entrySet().iterator();
    Map.Entry e;
    for (String key : lista.keySet()) {
        Integer i = lista.get(key);
        if (max < i)
            max = i;
    }
    System.out.println(max);
    max = 0;
    while (iter.hasNext()) {
        e = (Map.Entry) iter.next();
        String xy = (String) e.getKey();
        String[] datos = xy.split(",");
        int x = Integer.parseInt(datos[0]);
        int y = Integer.parseInt(datos[1]);
        matrix[y][x] += (int) e.getValue();
        double aux;
        if ((aux = normalMatrix(matrix, y, x, ((int) e.getValue()) * 4)) > max) {
            max = aux;
        }
        //normalMatrix(matrix,x,y,20);
        if (matrix[y][x] > max)
            max = matrix[y][x];
    }
    int A, R, G, B, n;
    for (int i = 0; i < xmax; ++i) {
        for (int j = 0; j < ymax; ++j) {
            if (matrix[j][i] != 0) {
                n = (int) Math.round(matrix[j][i] * 100 / max);
                R = Math.round((255 * n) / 100);
                G = Math.round((255 * (100 - n)) / 100);
                B = 0;
                A = Math.round((255 * n) / 100);
                ;
                if (R > 255)
                    R = 255;
                if (R < 0)
                    R = 0;
                if (G > 255)
                    G = 255;
                if (G < 0)
                    G = 0;
                if (R < 50)
                    A = 0;
                graph1.setColor(new Color(R, G, B, A));
                graph1.fillOval(i, j, 1, 1);
            }
        }
    }
    //graph1.dispose();

    ImageIO.write(img, "png", new File("example.png"));
    System.out.println(max);

    graph1.setColor(Color.RED);
    // Extraer elementos
    Elements e1 = doc.body().getAllElements();
    int i = 1;
    ArrayList<String> tags = new ArrayList<String>();
    for (Element temp : e1) {

        if (tags.indexOf(temp.tagName()) == -1) {
            tags.add(temp.tagName());

            List<WebElement> query = driver.findElements(By.tagName(temp.tagName()));
            for (WebElement temp1 : query) {
                Point po = temp1.getLocation();
                Dimension d = temp1.getSize();
                if (d.width <= 0 || d.height <= 0 || po.x < 0 || po.y < 0)
                    continue;
                System.out.println(i + " " + temp.nodeName());
                System.out.println("  x: " + po.x + " y: " + po.y);
                System.out.println("  width: " + d.width + " height: " + d.height);
                graph1.draw(new Rectangle(po.x, po.y, d.width, d.height));
                ++i;
            }
        }
    }

    graph1.dispose();
    ImageIO.write(img, "png", new File(PATH + NAME));

    driver.quit();

}

From source file:br.eti.kinoshita.selenium.SeleniumWebTest.java

License:Open Source License

/**
 * <p>Adds a screen shot to the list of attributes. TestNG has a strange 
 * behavior when adding attributes to a context. Although I am adding 
 * attributes to a context from within a method, it does not maintain 
 * your attributes separated per method. So, say you want to add the 
 * same attribute in different methods. You will have a hard time debugging 
 * until you realize sometimes it is simply replacing your attributes. 
 * Bummer.</p>/*  ww  w .j a  v a 2  s.c  om*/
 * 
 * <p>We are adding all screen shots as image/png. This may lead to 
 * troubles in the future, so probably it will change soon. The 
 * title of your screen shot will be its name (no creativity, sorry).</p>
 * 
 * <p>TBD: Check if we can add a way to pass the file type as parameter.</p>
 * 
 * @param context TestNG test context.
 * @param method TestNG test method, to which we will link your attribute to.
 * @param description Screen shot description.
 */
public void addScreenShot(ITestContext context, Method method, String description) {
    if (driver instanceof TakesScreenshot) {
        LOGGER.debug("Taking screenshot with driver " + driver.getTitle());
        File attachment = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        SeleniumScreenshot screenshot = new SeleniumScreenshot(attachment, description, "image/png",
                attachment.getName());
        this.addScreenShot(context, method, screenshot);
    } else {
        // We know usually the user wouldn't be able to use a HTML driver as 
        // we are checking in the static constructor, however I am paranoid 
        // with me users :)
        LOGGER.warn("Driver " + driver.getTitle()
                + " does not support taking screenshots. Use a different one please.");
    }
}

From source file:br.gov.frameworkdemoiselle.behave.runner.webdriver.WebDriverRunner.java

License:Open Source License

public File saveScreenshot() {
    return ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
}

From source file:br.gov.frameworkdemoiselle.behave.runner.webdriver.WebDriverRunner.java

License:Open Source License

public File saveScreenshotTo(String fileName, boolean generateSource) {
    File screenshotFile = new File(fileName);

    screenshotFile.getParentFile().mkdirs();

    driver.manage().window().maximize();

    File screenshot = null;/*from www  .j  a  v a  2 s . c  o m*/

    if (BehaveConfig.getRunner_screenShotZoomout() != 0) {
        WebElement html = driver.findElement(By.tagName("html"));

        for (int x = 0; x < BehaveConfig.getRunner_screenShotZoomout(); x++) {
            html.sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT));
        }

        screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        html.sendKeys(Keys.chord(Keys.CONTROL, "0"));
    } else {
        screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    }

    if (screenshot != null) {
        try {
            FileUtils.copyFile(screenshot, new File(screenshotFile.getAbsolutePath()));

            if (generateSource) {
                writeHtmlFile(screenshotFile.getAbsolutePath());
            }
        } catch (IOException e) {
            throw new BehaveException(message.getString("exception-save-screenshot"), e);
        }
    }

    return screenshotFile;
}

From source file:br.ufmg.dcc.saotome.beholder.selenium.listener.ScreenshotListener.java

License:Apache License

@Override
public void onTestFailure(ITestResult tr) {

    if (tr != null) { // tr is null only for test purposes.
        super.onTestFailure(tr);
    }//from  w ww. j a v  a 2 s . c om

    try {
        FileInputStream screenshot = new FileInputStream(
                ((TakesScreenshot) ListenerGateway.getDriver()).getScreenshotAs(OutputType.FILE)); // Take the
        // screenshot
        File screenshotFile = createFile(tr, createFolder(tr));
        Files.copyFile(screenshot, screenshotFile); // Copy the screenshot
        // to a repository
        // folder
    } catch (FileNotFoundException e) {
        this.logger.error(ErrorMessages.ERROR_FILE_NOT_FOUND_EXCEPTION, e);
    } catch (IOException e) {
        this.logger.error(ErrorMessages.ERROR_IO_EXCEPTION, e);
    } catch (Exception e) {
        this.logger.error(ErrorMessages.ERROR_UNKNOWN, e);
    }
}

From source file:ca.nrc.cadc.web.selenium.AbstractWebApplicationIntegrationTest.java

License:Open Source License

protected void captureScreenShot(final String outputFileName) throws IOException {
    final String filename = outputFileName + ".png";
    final WebDriver augmentedDriver = new Augmenter().augment(driver);
    final File sourceFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);

    FileUtils.copyFile(sourceFile, new File("./" + filename));

    System.err.println(String.format("Saved screenshot as '%s'", filename));
}

From source file:capture.Capture.java

@SuppressWarnings("unchecked")
public void takeScreen(Map<String, LinkInfo> map, String unique, String dir2) {
    Set<String> set = map.keySet();
    for (String url : set) {
        try {//from w w  w. ja v  a 2s  .  c  o m
            LinkInfo link = map.get(url);
            if (site.hasAuthentication()) {
                driver.navigate().to(site.setUrlWithAuth(url));
            } else {
                driver.navigate().to(url);
            }
            driver.navigate().to(url);
            //            System.out.println("Capturing screenshot: " + url);
            driver.getScreenshotAs(OutputType.FILE);
            File saveTo = new File(dir, url.hashCode() + ".png");
            File scrFile = driver.getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(scrFile, saveTo);
            link.setScreenshot(scrFile.getAbsolutePath());
            System.out.println("Screenshot captured: " + url);
        } catch (Exception ex) {
            Logger.getLogger(Capture.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    try {
        ObjectInputStream inp = new ObjectInputStream(new BufferedInputStream(
                new FileInputStream(new File(dir2 + File.separator + unique + ".bin"))));
        Map<String, Object> siteInfo = (Map<String, Object>) inp.readObject();
        inp.close();
        siteInfo.put("map", map);
        ObjectOutputStream op = new ObjectOutputStream(new BufferedOutputStream(
                new FileOutputStream(new File(dir2 + File.separator + unique + ".bin"))));
        op.writeObject(siteInfo);
        op.close();
    } catch (IOException | ClassNotFoundException ex) {
        Logger.getLogger(Capture.class.getName()).log(Level.SEVERE, null, ex);
    }
    builder.destroy();
}

From source file:cc.gospy.example.basic.SeleniumDemo.java

License:Apache License

public static void main(String[] args) {
    String phantomJsPath = "D:/Program Files/PhantomJS/phantomjs-2.1.1-windows/bin/phantomjs.exe";
    String savePath = "D:/screenshot.png";
    Gospy.custom().setScheduler(Schedulers.VerifiableScheduler.custom().setPendingTimeInSeconds(60).build())
            .addFetcher(Fetchers.TransparentFetcher.getDefault()).addProcessor(Processors.PhantomJSProcessor
                    .custom().setPhantomJsBinaryPath(phantomJsPath).setWebDriverExecutor((page, webDriver) -> {
                        TakesScreenshot screenshot = (TakesScreenshot) webDriver;
                        File src = screenshot.getScreenshotAs(OutputType.FILE);
                        FileUtils.copyFile(src, new File(savePath));
                        System.out.println("screenshot has been saved to " + savePath);
                        return new Result<>();
                    }).build())//  w w w . j av  a  2s  .co  m
            .build().addTask("phantomjs://http://www.zhihu.com").start();
}