HomeCodeHow to Take Screenshot and Save to MSSQL Database using Java and...

How to Take Screenshot and Save to MSSQL Database using Java and Selenium Webriver

This is to take Screenshot using Selenium Webdriver and to save in MS SQL Database. The image is saving in the database with the image name append with browser name, browser version, sequence number, and scenario name. This code is supported by Chrome, Firefox, Internet Explorer, and Safari.

There is one more option between line 63-70 to save the picture into a local folder if you want. You can set a folder in the local system and it will save the picture into the folder you specified in png format and byte format in MSSql Database.

Take Screenshot and save to MSSQL Database using Java and Selenium Webriver

package com.main;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.RemoteWebDriver;

public class ImageSave {
private static int imageSeqNo = 0;
private static String scenName;
private static WebDriver browserDriver;
private static int browserWidth;
private static int browserHeight;
public static String browser;
public static WebDriver driver;

public static int getBrowserWidth() {
return browserWidth;
}

public static int getBrowserHeight() {
return browserHeight;
}

public static String getScenName() {
return scenName;
}

public static int getImageSeqNo() {
return imageSeqNo;
}

public static void main(String[] args) throws Exception {
// BrowserDriver.getCurrentDriver();
}

public static void addScreenshot(WebDriver driver) throws IOException,
ClassNotFoundException, InterruptedException {

byte[] scrByte = getScreenShotBytes(driver);

browser = getBrowserAndVersion();
String scenarioName = getScenName();
String imageName = scenarioName + ” ” + browser + ” ”
+ System.currentTimeMillis() + “.png”;

File scrFile = getScreenShotFile(driver);
String screenWidthHeight = getImageWidthHeight(scrFile);
// if want to save screen shot picture in local system, enable line below
// FileUtils.copyFile(scrFile, new File(“C://screenshot//” + imageName));
insertImageDB(scrByte, scenarioName, imageName, screenWidthHeight,
browser);
Thread.sleep(1000);
}

public static String getImageWidthHeight(File imageFile) throws IOException {
BufferedImage bimg = ImageIO.read(imageFile);
int imageWidth = bimg.getWidth();
int imageHeight = bimg.getHeight();
if (imageWidth != 0) {
return imageWidth + “x” + imageHeight;
} else {
return “FullScreenx” + imageHeight;
}

}

public static File getScreenShotFile(WebDriver driver) {
// WebDriver driverA = new Augmenter().augment(driver);
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
}

public static byte[] getScreenShotBytes(WebDriver driver) {
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}

public static void insertImageDB(byte[] imageByte, String scenName,
String imageName, String screenWidthHeight, String browser)
throws ClassNotFoundException {
Properties dbProp = new Properties();
InputStream dbPropInput = null;
ResultSet rs = null;
PreparedStatement ps = null;
Connection con = null;
//setImageSeqNo(getImageSeqNo() + 1);
int seqNo = getImageSeqNo();
System.out.println(scenName + ” —- ” + browser + ” —- ”
+ screenWidthHeight + ” —- Shot Number: ” + seqNo);

try {
String propPath = “.\src\test\resources\props\dbConnect.properties”;
dbPropInput = new FileInputStream(propPath);
dbProp.load(dbPropInput); // load property file
String dbDriver = (dbProp.getProperty(“dbDriver”));
String dbURL = (dbProp.getProperty(“dbURL”));
String stPro = (dbProp.getProperty(“SPSql”));

Class.forName(dbDriver);
con = DriverManager.getConnection(dbURL);
ps = con.prepareStatement(stPro);

java.util.Date date = new java.util.Date();
java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(date.getTime());
System.out.println(“Image Timestamp=” + sqlTimestamp);

ps.setEscapeProcessing(true);
ps.setQueryTimeout(90); // timeout value may disable later, picture

ps.setString(1, “Project”);
ps.setString(2, scenName);
ps.setString(3, browser);
ps.setString(4, screenWidthHeight);
ps.setTimestamp(5, sqlTimestamp);
ps.setInt(6, seqNo);
ps.setString(7, imageName);
ps.setBytes(8, imageByte);
// comment below line to disable data base updating
ps.executeUpdate();

} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (dbPropInput != null)
dbPropInput.close();
if (rs != null)
rs.close();
if (ps != null)
ps.close();
if (con != null)
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

public static String getBrowserAndVersion() {
String browser_version = null;
Capabilities cap = ((RemoteWebDriver) driver).getCapabilities();
String browsername = cap.getBrowserName();
// This block to find out IE Version number
if (“internet explorer”.equalsIgnoreCase(browsername)) {
String uAgent = (String) ((JavascriptExecutor) driver)
.executeScript(“return navigator.userAgent;”);
System.out.println(uAgent);
// uAgent return as “MSIE 8.0 Windows” for IE8
if (uAgent.contains(“MSIE”) && uAgent.contains(“Windows”)) {
browser_version = uAgent.substring(uAgent.indexOf(“MSIE”) + 5,
uAgent.indexOf(“Windows”) – 2);
} else if (uAgent.contains(“Trident/7.0”)) {
browser_version = “11.0”;
} else {
browser_version = “00”;
}
} else {
// Browser version for Firefox and Chrome
browser_version = cap.getVersion();// .split(“.”)[0];
}
String browserversion = browser_version.substring(0,
browser_version.indexOf(“.”));
String bVersion = String.format(“%02d”, Integer.parseInt(browserversion));
return ((browsername) + “_” + bVersion);
}

public static String browserNameConvert(String browser_name) {
if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(
browser_name, “explorer”)) {
return “IE”;
} else if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(
browser_name, “firefox”)) {
return “FF”;
} else if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(
browser_name, “chrome”)) {
return “CH”;
} else if (org.apache.commons.lang3.StringUtils.containsIgnoreCase(
browser_name, “safari”)) {
return “SF”;
} else {
return “NA”;
}
}
}

Related:
How to Convert Picture into Byte, Get Image Width and Height using Java

MSSQL Database Connection Property file with user credentials and Store Procedure

##################dbConnect.properties##################
dbDriver=com.microsoft.sqlserver.jdbc.SQLServerDriver
dbURL=jdbc:sqlserver://YOURSERVERURL;database=DATABASENAME;user=USERNAME;password=PASSWORD
SPSql={call STOREPROCEDURE (?,?,?,?,?,?,?,?)}

To save in database, the store procedure already created in this example and all these data for database connection and store procedure is listed in the property file.

The browser name converting to 2 char short forms like FF(Firefox), CH (Chrome) etc. This is also capable of finding browser version programmatically including Internet Explorer version number. This script supports Internet Explorer versions 8,9,10,11.

Disclosure: Mashtips is supported by its audience. As an Amazon Associate I earn from qualifying purchases.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

You May Like

More From Author