Friday, 17 February 2017

release the port in windows OS


Windows OS:


cmd> netstat -ano | findstr 8080

lists who is using port 8080 and related process id

port  - pid
8080 - 13892

do you want to kill process ?
taskkill /f /pid 13892

SUCCESS

Thursday, 16 February 2017

Read soap xml file using xpath



import org.apache.xmlbeans.impl.xb.xsdschema.FieldDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.FileReader;


public class SoapReaderUsingXpath {
    public static void main(String[] args){
        String result ="";
        String soapXmlFile;
        DocumentBuilderFactory dbf;
        DocumentBuilder db;
        Document doc;
        XPath xpath;
        Node nl;
        soapXmlFile="C:\\wssoap.xml";
        String myXpath="//Element/Body/Node1/text()";
        try{
            dbf=DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(false);
            db=dbf.newDocumentBuilder();
            doc=db.parse(new InputSource(new FileReader(soapXmlFile)));
            xpath= XPathFactory.newInstance().newXPath();
            nl=(Node)xpath.evaluate(myXpath,doc.getDocumentElement(), XPathConstants.NODE);
            result=nl.getNodeValue();
        }
        catch (Exception ex){}

    }
}

Read text file?




BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
}

Tuesday, 14 February 2017

Read xml file content


import java.io.*;
import java.nio.charset.Charset;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

import org.w3c.dom.NodeList;

public class NewTest {

    public static void main(String[] args) throws IOException, SOAPException {

        String xmlInput = getTexFromXML("C:\\Inboud_testfile_before.xml");
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage message = factory.createMessage(
                new MimeHeaders(),
                new ByteArrayInputStream(xmlInput.getBytes(Charset
                        .forName("UTF-8"))));
        SOAPBody body = message.getSOAPBody();
        getValue(body,"REC_MEME","MEME_CK",0);
    }

    private static String getTexFromXML(String xmlPath) {
        String xmlInput;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(new File(xmlPath)));

            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line.trim());
            }
            xmlInput = sb.toString();
            return xmlInput;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlPath;
    }

    public static void getValue(SOAPBody body, String parentNode, String childNode, Integer position)
    {
        NodeList returnList = body.getElementsByTagName(parentNode);
        for (int k = 0; k < returnList.getLength(); k++) {
            if(position==k) {
                NodeList innerResultList = returnList.item(k).getChildNodes();
                for (int l = 0; l < innerResultList.getLength(); l++) {
                    if (innerResultList.item(l).getNodeName()
                            .equalsIgnoreCase(childNode)) {
                        System.out.println(Integer.valueOf(innerResultList.item(l)
                                .getTextContent().trim()));
                    }
                }
            }
        }
    }
}

Monday, 6 February 2017

basics of bitbucket version control tool

Bitbucket is another distributed version control tool from Atlasian.



Setup:

Prerequisite 1:

Go to https://bitbucket.org/ and create an account with gmail id and verify email id ( check your gmail inbox for verification).

Prerequisite 2:  

We have two have two options to choose ( Git and Mercurial , I choose Git)
Download GitHub here ( https://git-scm.com/downloads)


Create Repository:
Be on bitbucket.org and click on repositories -> create repository -> Enter name “MyFirstRepo”, choose Repository type as Git and then click on “Create repository”.



Here is your Repo:
https://EmailId@bitbucket.org/Accountname/myfirstrepo.git




Now onwards We just need to follow git hub commands.

·         Open Project folder in Explorer
·         Right click and select Git bash
·         $git init
·         $git add *
·         $git commit –m “my first commit”
·         $git remote add origin https://github.com/kasthurikranthikumar/EmptyMavenProject.git
·         $git push origin master


Now Lets create pull request:

 Actions -> Create pull Request
Same as git hub.



Thursday, 2 February 2017

page factory framework for selenium web automation

Here is my way of implementing selenium page factory framework.
yes, this framework can be modified to suite, pom , data driven, keyword driven framework.

Here is my Framework structure:



BaseDriver.java ( Here Driver creation happens)

package com.companyName.automation_one.web.pom.driver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import com.companyName.automation_one.utils.PropertiesReaderUtility;

public class BaseDriver {

public static WebDriver driver;

public static void startSession() {
String browser, remote, baseUrl;
URL hub_url = null;
String user_dir = System.getProperty("user.dir");

PropertiesReaderUtility prop = new PropertiesReaderUtility(user_dir + "/selenium.properties");
browser = System.getProperty("browser", prop.getProperty("browser"));
remote = System.getProperty("remote.webdriver", prop.getProperty("remote.webdriver"));
baseUrl = System.getProperty("baseurl.dev", prop.getProperty("baseurl.dev"));
try {
hub_url = new URL(System.getProperty("hub.url", prop.getProperty("hub.url")));
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (driver == null) {
if (remote.equalsIgnoreCase("false"))

switch (browser) {
case "firefox":
System.setProperty("webdriver.firefox.driver",
user_dir + "\\src\\ExternalJars\\geckodriver\\geckodriver.exe");
driver = new FirefoxDriver();
break;
case "chrome":
System.setProperty("webdriver.chrome.driver",
user_dir + "\\src\\ExternalJars\\chromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
break;
case "ie":
System.setProperty("webdriver.ie.driver",
user_dir + "\\src\\ExternalJars\\IEDriverServer_x64_2.25.3\\IEDriverServer.exe");

DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(ieCapabilities);
break;
}
else
switch (browser) {
case "firefox":
System.setProperty("webdriver.firefox.driver",
user_dir + "\\src\\ExternalJars\\geckodriver\\geckodriver.exe");
FirefoxProfile fp = new FirefoxProfile();
DesiredCapabilities dc_ff = DesiredCapabilities.firefox();
dc_ff.setCapability(FirefoxDriver.PROFILE, fp);
driver = new RemoteWebDriver(hub_url, dc_ff);

break;
case "chrome":
System.setProperty("webdriver.chrome.driver",
user_dir + "\\src\\ExternalJars\\chromeDriver\\chromedriver.exe");
ChromeOptions chr_options = new ChromeOptions();
DesiredCapabilities dc_chr = DesiredCapabilities.chrome();
dc_chr.setCapability(ChromeOptions.CAPABILITY, chr_options);
driver = new RemoteWebDriver(hub_url, dc_chr);

break;
case "ie":
System.setProperty("webdriver.ie.driver",
user_dir + "\\src\\ExternalJars\\IEDriverServer_x64_2.25.3\\IEDriverServer.exe");
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new RemoteWebDriver(hub_url, ieCapabilities);
break;
}
}
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.get(baseUrl);
driver.manage().window().maximize();
}

public static void stopSession() {
driver.quit();
driver = null;
}
}



LoginPage.java ( Here, we keep locators and methods related to one page  )

package com.companyName.automation_one.web.pom.pages.login;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;

import com.companyName.automation_one.web.pom.driver.BaseDriver;

public class LoginPage {
WebDriver driver;

@FindBy(how = How.ID, using = "userName")
WebElement userName;
@FindBy(how = How.ID, using = "password")
WebElement password;
@FindBy(how = How.ID, using = "submit")
WebElement submit;
public LoginPage() throws Exception {
this.driver = BaseDriver.driver;
PageFactory.initElements(driver, LoginPage.class);
}

public void login(String uname, String pwd) {
userName.sendKeys(uname);
password.sendKeys(pwd);
submit.click();
}

}


BaseTest,java ( which is a parent class for each testClass )

package com.companyName.automation_one.web.pom.tests.login;

import org.junit.AfterClass;
import org.junit.BeforeClass;

import com.companyName.automation_one.web.pom.driver.BaseDriver;

public class BaseTest {
@BeforeClass
public void setup() {
BaseDriver.startSession();

@AfterClass
public void cleanup() {
BaseDriver.stopSession();
}
}

LoginTest.java ( this is one test class)

package com.companyName.automation_one.web.pom.tests.login;

import org.testng.Assert;
import org.testng.annotations.Test;

import com.companyName.automation_one.web.pom.pages.login.LoginPage;

public class LoginTest extends BaseTest {

@Test
public void Method1() throws Exception {
LoginPage lp=new LoginPage();
lp.login("test", "test");
Assert.assertTrue(true);
}

}

BaseDriver / Driver Factory for selenium Framework using "singleton" Design Pattern.

Every other kind of selenium framework need one awesome utility to create driver object in generic way.

here is my way.

i used singleton design pattern for the same.


package com.companyname.automation_one.web.pom.driver;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import com.companyname.automation_one.utils.PropertiesReaderUtility;

public class BaseDriver {

public static WebDriver driver;

public static void startSession() {
String browser, remote, baseUrl;
URL hub_url = null;
String user_dir = System.getProperty("user.dir");

PropertiesReaderUtility prop = new PropertiesReaderUtility(user_dir + "/selenium.properties");
browser = System.getProperty("browser", prop.getProperty("browser"));
remote = System.getProperty("remote.webdriver", prop.getProperty("remote.webdriver"));
baseUrl = System.getProperty("baseurl.dev", prop.getProperty("baseurl.dev"));
try {
hub_url = new URL(System.getProperty("hub.url", prop.getProperty("hub.url")));
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (driver == null) {
if (remote.equalsIgnoreCase("false"))

switch (browser) {
case "firefox":
System.setProperty("webdriver.firefox.driver",
user_dir + "\\src\\ExternalJars\\geckodriver\\geckodriver.exe");
driver = new FirefoxDriver();
break;
case "chrome":
System.setProperty("webdriver.chrome.driver",
user_dir + "\\src\\ExternalJars\\chromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
break;
case "ie":
System.setProperty("webdriver.ie.driver",
user_dir + "\\src\\ExternalJars\\IEDriverServer_x64_2.25.3\\IEDriverServer.exe");

DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(ieCapabilities);
break;
}
else
switch (browser) {
case "firefox":
System.setProperty("webdriver.firefox.driver",
user_dir + "\\src\\ExternalJars\\geckodriver\\geckodriver.exe");
FirefoxProfile fp = new FirefoxProfile();
DesiredCapabilities dc_ff = DesiredCapabilities.firefox();
dc_ff.setCapability(FirefoxDriver.PROFILE, fp);
driver = new RemoteWebDriver(hub_url, dc_ff);

break;
case "chrome":
System.setProperty("webdriver.chrome.driver",
user_dir + "\\src\\ExternalJars\\chromeDriver\\chromedriver.exe");
ChromeOptions chr_options = new ChromeOptions();
DesiredCapabilities dc_chr = DesiredCapabilities.chrome();
dc_chr.setCapability(ChromeOptions.CAPABILITY, chr_options);
driver = new RemoteWebDriver(hub_url, dc_chr);

break;
case "ie":
System.setProperty("webdriver.ie.driver",
user_dir + "\\src\\ExternalJars\\IEDriverServer_x64_2.25.3\\IEDriverServer.exe");
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new RemoteWebDriver(hub_url, ieCapabilities);
break;
}
}
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.get(baseUrl);
driver.manage().window().maximize();
}

public static void stopSession() {
driver.quit();
driver = null;
}
}

Wednesday, 1 February 2017

Api testing : Get

Simple GetApi code:

Maven dependency:
<!--For Http Get/Post/ect we need HTTP client libs :: http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>



<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>


import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;

public class TestGet {

public static void main(String[] args) {

String url = "https://httpbin.org/get";
HttpResponse response = null;

HttpClientBuilder builder = HttpClientBuilder.create();
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
builder.setConnectionManager(connectionManager);
HttpClient httpclient = builder.build();
RequestConfig requestConfig = RequestConfig.custom()
/*
* connectionRequestTimeout happens when you have a pool of
* connections and they are all busy, not allowing the
* connection manager to give you one connection to make the
* request.
*/
.setConnectionRequestTimeout(30000)
/*
* connectTimeout happens when establishing the connection. For
* instance while doing the tcp handshake.
*/
.setConnectTimeout(30000)
/*
* socketTimeout: is the timeout while waiting for data. Usually
* happens when your server is slow
*/
.setSocketTimeout(30000).build();
try {
HttpGet httpget = new HttpGet(url);
httpget.setConfig(requestConfig);
response = httpclient.execute(httpget);
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = new JSONObject(responseBody);
System.out.println(jsonObj.get("origin"));
//Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
} catch (IOException ex) {

}

}

}

Json utils

As part of api testing, we might need to play with json objects, arrays and key-value pairs.

here is the solution.


Maven dependency:

<!-- Rest Utils Returns JsonObject :: http://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>

Java code:



import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

/**
 * Class which consists of differnt methods related to Json Utils
 */
public class JsonUtils {

/**
* Method to Converts given String to JSON object
*
* @param str
* @return json Object
*/
public static JSONObject getJsonObjectFromString(String str) {
return new JSONObject(str);
}

/**
* Method to Converts given String to JSON Array
*
* @param str
* @return json array
*/
public static JSONArray getJsonArrayFromString(String str) {
return new JSONArray(str);
}

/**
* method to read json object form resp object
*
* @param response
* @return json object
*/
public static JSONObject getJsonFromResponse(HttpResponse response) {
String responseBody = null;
try {
responseBody = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jsonObj = new JSONObject(responseBody);
return jsonObj;
}

/**
* method to read json array form resp object
* @param response
* @return JsonArray
* @throws JSONException
*/
public static JSONArray getJsonArrayFromResponse(HttpResponse response) {
String responseBody = null;
try {
responseBody = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
JSONArray jsonObj = new JSONArray(responseBody);
return jsonObj;
}

/**
* Method to read value from json for the said key
*
* @param jsonObj
* @param key
* @return
*/
public static Object getValueFromJson(JSONObject jsonObj, String key) {
Object propertyUtilityCount = 0;
propertyUtilityCount = jsonObj.get(key);
return propertyUtilityCount;
}

/**
* Method to read json array from json object for the said key
*
* @param jsonObj
* @param key
* @return
*/
public static JSONArray getSaidJSonArrayFromJson(JSONObject jsonObj, String key) {
Object object = jsonObj.getJSONArray(key);
if (object instanceof JSONArray) {
return (JSONArray) object;
} else {
throw new JSONException(key + " JSONObject is not a JSONArray.");
}
}

/**
* Fetch the object with in an array and through index we fetch which Object
* we want to fetch
*
* @param getResponse
* @param i
* @return
* @throws IOException
*/
public static JSONObject getJsonArrayFromJsonObject(HttpResponse getResponse, int i) {

String result = "";
try {
result = EntityUtils.toString(getResponse.getEntity());
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
JSONArray e = new JSONArray(result);
JSONObject obj = e.getJSONObject(i);
return obj;
}

/**
* Method to fetch json object from json array for the said index
*
* @param jsonArray
* @param i
* @return json object
*/
public static JSONObject getSaidJsonObjectFromJsonArray(JSONArray jsonArray, int i) {
JSONObject obj = new JSONObject();
obj = jsonArray.getJSONObject(i);
return obj;
}

/**
* Method to fetch json object from json object for the said key
*
* @param jsonObj
* @param key
* @return json object
*/
public static JSONObject getSaidJsonObjectFromJsonObject(JSONObject jsonObj, String key) {
JSONObject obj = new JSONObject();
obj = jsonObj.getJSONObject(key);
return obj;
}

/**
* Method to fetch json object from json object
*
* @param jsonObj
* @return json object
*/
public static JSONObject getSaidJsonObjectFromJsonObject(JSONObject jsonObj) {
JSONObject obj = new JSONObject();
return obj;
}

/**
* verifies that given json is empty or not
*
* @param json
*            obj
* @return boolean value
*/
public static boolean isNonEmpty(JSONObject obj) {
boolean result = false;
if (obj.length() <= 0 || obj != null) {
result = true;
}
return result;
}

/**
* checks the given json array is empty or not
*
* @param obj
* @return boolean value
*/
public static boolean isNonEmpty(JSONArray obj) {
boolean result = false;
if (obj.length() <= 0 || obj != null) {
result = true;
}
return result;
}

/**
* converts json object to xml
*
* @param jsonObj
* @return String
*/
public String toXML(JSONObject jsonObj) {
String xml = XML.toString(jsonObj);
return xml;
}

}

Excell read / update using apache libs

Here is the Maven dependency:
<!-- THis is to read and write excel sheest for data and other purposes:
https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>

add below one, if not a maven project i.e manual jar adition

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>


Code:


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * Method to read and update Excel sheet
 */
public class ExcelReader {
private Cell openCell;
private Row openRow;
private Sheet openSheet;
private String data;
private Workbook openWorkbook;
InputStream inp;
File f;

/**
* Creates an Excel reader object and open the said workbook at the
* specified path.
*
* @param excelPath
*            - The path of the excel file
*/
public ExcelReader(String excelPath) throws Exception {
this(new File(excelPath));
}

/**
* Creates an Excel reader object and open the said workbook at the
* specified path.
*
* @param excelFile
*            - File object of the excel file
*/
public ExcelReader(File excelFile) throws Exception {
f = excelFile;
inp = new FileInputStream(excelFile);
if (isXlsx(excelFile))
openWorkbook = new XSSFWorkbook(inp);
else
openWorkbook = new HSSFWorkbook(inp);
}

/**
* Returns true or false depending upon whether file name ends with xlsx
* * @param fl
*
* @return
*/
private boolean isXlsx(File fl) {
String fileName = fl.getName();
if (fileName.endsWith("xlsx"))
return true;
return false;
}

/**
* Open sheet with the specified name
*
* @param sheetName
*/
public void openSheet(String sheetName) {
openSheet = openWorkbook.getSheet(sheetName);
}

/**
* Gets current sheet name
*
* @param sheetNo
*            - Index of sheet
* @return - Sheet name
*/
public String getCurrentSheetName(int sheetNo) {
openSheet = openWorkbook.getSheetAt(sheetNo);
return openSheet.getSheetName();
}

/**
* Gets number of sheets in the given workbook
*
* @return - number of sheets in the workbook
*/
public int getNoOfSheets() {
return openWorkbook.getNumberOfSheets();
}

/**
* Gets the data from the currently opened sheet present on the specified
* row and column
*
* @param column
* @param row
* @return - Respective data in string format. "" if the said row -column
*         does not exist
*/
public String getData(int column, int row) {
try {

openRow = openSheet.getRow(row);
openCell = openRow.getCell(column);
@SuppressWarnings("deprecation")
int cellType = openCell.getCellType();
switch (cellType) {
case 0:
if (DateUtil.isCellDateFormatted(openCell)) {
Date dt = openCell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
data = sdf.format(dt);
} else
data = Long.toString(Math.round(openCell.getNumericCellValue()));
break;
case 1:
data = openCell.getRichStringCellValue().getString();
break;
case 2:
data = openCell.getRichStringCellValue().getString();
break;
case 3:
data = openCell.getRichStringCellValue().getString();
break;
case 4:
data = Boolean.toString(openCell.getBooleanCellValue());
break;
case 5:
data = Byte.toString(openCell.getErrorCellValue());
break;
default:
data = openCell.getRichStringCellValue().getString();
}

if (data == null) {
data = "";
}
return data;
} catch (Exception e) {
if (openRow == null || openCell == null || data == null) {
data = "";
return data;
} else {
System.out.println(e);
return "";
}
}

}

/**
* Number of rows in the said sheet.
*
* @return
*/
public int getNoOfRows() {
return (openSheet.getLastRowNum() + 1);
}

/**
* Number of columns in the first row of the sheet
*
* @return
*/
public int getNoOfColumn() {
Row rw = openSheet.getRow(0);
if (rw == null)
return 0;
return rw.getLastCellNum();
}

/**
* Number of columns of a particular row number that is specified
*
* @param rowNumber
* @return
*/
public int getNoOfColumn(int rowNumber) {
Row rw = openSheet.getRow(rowNumber);
if (rw == null)
return 0;
return rw.getLastCellNum();
}

/**
* Gets the current open sheet name
*
* @return
*/
public String getSheetName() {
return openSheet.getSheetName();
}

/**
* Updates current sheet with given data.
*
* @param col
* @param row
* @param data
*/
public void updateData(int col, int row, String data) {
try {
openRow = openSheet.getRow(row);
openCell = openRow.createCell(col);
openCell.setCellValue(data);
inp.close();
FileOutputStream out = new FileOutputStream(f);
openWorkbook.write(out);
out.close();
} catch (Exception ex) {
}

}
}

Generic utils for any project / Random number / String generators


here is the maven dependency.

<!--utils For Random Number / String generation:: https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>


Code:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.RandomStringUtils;

/**
 * a common utils class to generate random alphanumerics and project specific
 * strings
 *
 */
public class CommonUtils {

/**
* Method to generate random alpha numeric string of size 10
*
* @return
*/
public static String getRandomAlphaNumeric() {
return RandomStringUtils.randomAlphanumeric(10);
}

/**
* Method to generate random alphabet string of size 10
*
* @return
*/
public static String getRandomAlphabetic() {
return RandomStringUtils.randomAlphabetic(10);
}

/**
* Method to generate random numeric string of size 10
*
* @return
*/
public static String getRandomNumeric() {
return RandomStringUtils.randomNumeric(10);
}

/**
* Method to generate random numeric from the given max and min numbers
*
* @param max
* @param min
* @return
*/
public static int getRandomNumeric(int max, int min) {
Random rand = new Random();
int randomNum = rand.nextInt(max) + min;
return randomNum;
}

/**
* Method to generate random dates for checkin and checkout
*
* @return map of string, string
*/
public static HashMap<String, String> getDates() {
HashMap<String, String> map = new HashMap<String, String>();
int i = getRandomNumeric(285, 1);// checkin date
int j = getRandomNumeric(14, 1);// checkout date
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // date format
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, i); // Adding i days
String checkinDate = sdf.format(c.getTime());
map.put("CHECKIN", checkinDate);

c.add(Calendar.DATE, j); // Adding j days
String checkoutDate = sdf.format(c.getTime());
map.put("CHECKOUT", checkoutDate);
return map;
}

/**
* Method to generate random email id
*
* @return
*/
public static String getRandomEmailId() {
return "John" + RandomStringUtils.randomNumeric(10) + ".Smith@test.com";
}

/**
* Method to convert given millsecs to hours,min,secs and milli secs
*
* @param millis
* @return
*/
public static String timeConversion(long millis) {
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
String strMilli = TimeUnit.MILLISECONDS.toMillis(millis) % TimeUnit.MINUTES.toMillis(1) + "";

hms = hms + ":" + strMilli;
return hms;
}
}

Soft Assertion util. VerifyTestUtil

As part of the project, we might need to soft assert our assertions and show all error message at a time instead of breaking the execution then and their.

here is the solution.


import java.util.ArrayList;

import org.testng.Assert;

/**
 * Class to verify multiple assertions and sums of error messages
 *
 */
public class VerifyTestUtil {
private ArrayList<String> results = new ArrayList<String>();

/**
* method to verify one condition and add err message ot err list
*
* @param condition
* @param message
*/
public void verify(boolean condition, String message) {
if (!condition)
results.add(message);
}

/**
* final verification to check whether the test is passed or not
*
* @return
*/
public boolean isPassed() {
return results.size() == 0;
}

/**
* Method to read messages
*
* @return
*/
public String getMessage() {
return results.toString();
}

/**
* final method to execute
*
* @return
*/
public boolean assertTestResult() {
for (String str : results)
System.out.println(str);
Assert.assertTrue(results.size() == 0, results.toString());
return results.size() == 0;
}

/**
* verifies result
*
* @param message
* @return
*/
public boolean assertTestResult(String message) {
for (String str : results)
System.out.println(str);
Assert.assertTrue(results.size() == 0, message + " " + results.toString());
return results.size() == 0;
}

/**
* compare two strings and append err message if any
*
* @param one
* @param two
* @param message
* @return
*/
public boolean assertEqual(String one, String two, String message) {
if (one.contentEquals(two))
return true;
else {
results.add(message);
return false;
}
}

/**
* comares two integers
*
* @param one
* @param two
* @param message
* @return
*/
public boolean assertEqual(int one, int two, String message) {
if (one == two)
return true;
else {
results.add(message);
return false;
}
}

/**
* method to asserts  true
* @param condition
* @param message
*/
public void assertTrue(boolean condition, String message) {
Assert.assertTrue(condition, message);
}
}