Thursday, 16 February 2017

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;
}

}