MainMenu

Home Java Overview Maven Tutorials

Tuesday 28 August 2018

How to install Cucumber In rubymine

How to install Cucumber in rubymine



Hello Friends,
In this article i will describe that how can we install Cucumber in ruby mine & how can we create automation projects in Ruby Mine.



For Video :-

1).Open Your rubymine and copy the path of the project as shown below :-


2). Open commond prompt & paste the project path after cd and hit enter as below :-


3). Go to url https://rubygems.org/gems/cucumber/versions/2.4.0or click here and from the left pane click the copy to clipboard button as below


4). Now in commond promt paste the commond as copied above and hit the enter key


5). If below message in your commond prompt appears then congratulation cucumber have been installed in your rubymine




Next Topic :- Overview of Postman API Testing tool

Previous Topic :- Ruby basic programing Array, String & Methods

Sunday 26 August 2018

Basic program in ruby 2

Basic Programming in ruby Array, String, Methods



Hello Friends,
We will learn more about ruby programming that how to create Array, Access elements from array , String & methods


0). How to create an Array in Ruby :-

arr1 =Array.[](1,3,5,7,9)
puts arr1



Output :-

1
3
5
7
9


----------------------------------------------------
1). How to create an Array in Ruby by second way :-

arr2 = Array[2,4,6,8]
puts arr2



2
4
6
8
-------------------------------------------------------

2). How to get length an Array in Ruby :-

arr = Array.new(10)
puts array.length
puts arr.size
puts arr.length


Output :-

10
10


--------------------------------------------------------------
3). How to create a string Array in Ruby :-

arr3 = Array["chandan", "shina", "adhiraj", 2, 46, "akshat", "sarvakaram"]
puts arr3[2..5]


Output :-
adhiraj
2
46
akshat

--------------------------------------------------------------
4). String in Ruby :-

str = "chandanSingh"
puts str.capitalize
puts str.upcase
puts str.downcase
puts str.reverse
puts str.length
puts str[2]
puts str[2..4]


Output :-
Chandansingh
CHANDANSINGH
chandansingh
hgniSnadnahc
12
a
and

--------------------------------------------------------------
5). Methods in Ruby :-

def add(x, y)
puts x+y
end
add 10, 20
def language(a, b)
puts "best language for beginner is #{a}"
puts "second best language for beginner is #{ b}"
end
language "Ruby", "Core java"
def name(x= "chandan", y ="Shreya")
puts "my name is #{x}"
puts "my friend name is #{y}"
end
name
name "adhiraj" , "ritu"



Output :-
30
best language for beginner is Ruby
second best language for beginner is Core java
my name is chandan
my friend name is Shreya
my name is adhiraj
my friend name is ritu


--------------------------------------------------------------
6). How to pass multiple parameter in methods in Ruby :-

def multipara(*test)
puts "length of parameter is #{test.length}"
for i in 0..test.length-1
puts "Elements of parameter is #{test[i]}"
end
end
multipara "chandan", "Shina", "arti" ,"reena"





Output :-
length of parameter is 4
Elements of parameter is chandan
Elements of parameter is Shina
Elements of parameter is arti
Elements of parameter is reena



Next Topic :- How to configure cucumber in Ruby Mine

Previous Topic :- Basic Programming in ruby for, if-else, while do-while loop etc

Friday 24 August 2018

How to Download and install Ruby and Ruby mine

How to download and install ruby and rubymine in windows



Hello Friends,

In this article i will describe that how can we download and install ruby and ruby mine in windows machine.

A) Download & Install the Ruby
B) Download and install the ruby mine
C) Install the cucumber in ruby mine



1). Go to the website "https://rubyinstaller.org/" or Click Here

2). Click the Download button as shown in below screen


3). Select the file as per your computer as below
For example : my system is window 7 32 bit, so i will select Ruby 2.5.1-2 (x86) file to download


4). If you are facing any problem then you can directly download from my google drive as below
Click here to download Ruby from drive
Now double click on the setup and then click on Run button, then next .....as we install normal software.


5). To verify that ruby has been installed properly or not , open the commond prompt(cmd)
and Enter ruby -v and hit Enter key.
ruby version will appear and if so, congratulation ruby have installed in your machine.


6). To access "ruby interactive shell", type irb and hit Enter key as below


7). Now you can run your ruby program also from cmd as below


8). Download ruby editor Rubymine
a).go to the Url : https://www.jetbrains.com/ruby/download/ or click here
b).Click on the "Donwload" button to download the rubymine
Click here to download from driver


9). Install the ruby mine in your machine
double click on setup file & then click run button as below


Now as normal software installation click on next button and the next if required the finish


Now select the Ruby 2.5.1 as shown below and click on install button


Now click the finish button


Now launch the ruby mine and if you are launching/opening it first time then select "Do not import" radio button as below


10). Create your project/file & run the ruby programs


Now select the Ruby option from open matching files in ruby mine as below :-


11). Create a simple ruby program to print name "chandan singh"


12). Install the cucumber in rubymine
open the commond prompt(cmd) and type the commond gem install cucumber and hit enter, as below


Next Topic :- Basic Programming in ruby if else, for, while do while loop etc

Previous Topic :- Ruby Introduction

Thursday 23 August 2018

Basic Programs in Ruby

Basic Programming in ruby



Basic Programming in Ruby :-


0). How to print something in Ruby :-

print 'welcome to ruby'
puts 'hello ruby'
puts "hello again ruby"


Output :-welcome to rubyhello ruby
hello again ruby
Note :puts will change the row, but print will not.

--------------------------------------------------------------
1). Arithmatic Operator :-
Always remember ruby is case senstive.

x = 10
y =20
z = x+y
puts z
z = x*y
puts z
z = x-y
puts z
z = y/z
puts z

Output :-
30
200
-10
-2
--------------------------------------------------------------

2). If Else loop in ruby :-

x = 10
y = 20
if x>y
puts "x is greater than y"
else
puts "y is greater than x"
end

Output :-x is greater than y
-------------------------------------------------------------
3). While & Do while loop in ruby :-

x = 10
y = 20
while x<y do
x = x+1;
print "value of x is"
puts x
end



In the below code first value of x will be incremented and then printed after that condition will be checked

x = 10
y = 20
begin
x = x+1
puts x
end while x

Output in both the code:-
11
12
13
14
15
16
17
18
19
20
------------------------------------------------------
4).For Loop & for loop with break :-

for i in 0..5
puts i
end



Output :-
0
1
2
3
4
5

For loop with break statement

for i in 0..5
if i>2 then
break
end
puts i
end

Output :-
0
1
2


Next Topic :- Basic Programming in ruby Array, String & Methods etc

Previous Topic :- How to download and install Ruby & Rubymine

Ruby Tutorials

Ruby Tutorials



For Video Tutorial : Move on Youtube Channel


Note : Select the playlist as per your need & move with number sequence













1.Introduction of Ruby

2.Download & Install Ruby


3.Basic Programs in Ruby Part 1


4. Basic Programming in Ruby Part 2


4.1. How to install Cucumber in rubymine


5.Introduction of API Testing tool Postman


6.


7.


8.


9.


10.


11.


12.


13.


14.


15.


16.


17.


18.


19.


20.


21.


22.


23.


24.




25.


26.
27.


28.
29.


30.
31.











Java Tutorial

Learn Ruby

Java for beginner

Ruby programming Tutorial

Java course

Ruby Programming for beginner

Java Online Course

Learn Ruby Online

Wednesday 22 August 2018

Ruby Introduction

A brief intro of ruby



Hello Friends,
In this article , i will describe about Scripting Language Ruby :-


Ruby :-

>> was created by "Yukihiro Matsumoto" in mid of 1990.
>>Ruby is an open-source and is freely available on the web, but it is subject to a license.
>> A programmer's best friend
>> It runs on variety of platforms such as windows, Mac OS and the various version of Unix.
>> Ruby is a true object-oriented programming language.
>> Dynamic >> Open source programming language with a focus on simplicity and productivity.
>> It has an elegant syntax that is natural to read and easy to write.
>> Used for internet application.
>> Ruby can be used to write Common Gateway Interface (CGI) scripts.
>> Ruby can be embedded into Hypertext Markup Language (HTML).
>> Twitter Github are developed using ruby etc.
>> A simple programming practice(INTRO).
>> Extension of Ruby program file is ".rb".
>> comment in ruby is followed by "#".


Different Naming conventions in Ruby

Ruby defines some naming conventions for its variable, method, constant and class.
Constant: Starts with a capital letter.
Global variable: Starts with a dollar sign ($).
Instance variable: Starts with a (@) sign.
Class variable: Starts with a (@@) sign.
Method name: Allowed to start with a capital letter.



Next Topic :-

How to Download & Install Ruby & Rubymine

Sunday 1 July 2018

How to perform upload operation in selenium

How to upload the file using selenium

Click Here to navigate on practice page



Hello Friends, In this tutorial we will learn how to perform upload operation in selenium.
We can perform the upload operation in selenium by two ways :
1). First by SendKeys() method.
2). Second by using the robot class.
First Method :
Precondition : Element should be input and type should be "file", as shown below :



Now we just need to locate the element and just use the method sendKeys() and in sendKeys() method we will pass the path of that file.
Syntax :-
driver.findElement(By.xpath("path of element")).sendKeys("path on file");

Here is sample code :-

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Uploadfile
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\cchauhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
/*FirefoxOptions foptions = new FirefoxOptions();
foptions.setCapability("marionette", false);
driver = new FirefoxDriver(foptions);*/
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com/p/this-webpage-is-designed-for-selenium.html");
Thread.sleep(3000);
}
@Test
public void h()
{
//Remember element should be input and type should be "file"
driver.findElement(By.xpath(".//*[@id='post-body-2064404811754288590']/form[1]/input[1]")).sendKeys("C:\\Users\\cchauhan\\Desktop\\wallpaper.png");
}
}





Second Method : By using Robot Class:-
What is Robot class ?
"Basically robot class will simulate the Keyboard and mouse actions."
Steps :-
1). First Copy the file path.
2).Paste the file path in popup window
3).Press Enter button.

by robot class we can perform CTRL + C operation by below methods as :-
StringSelection ss = new StringSelection("C:\\Users\\cchauhan\\Desktop\\wallpaper.png");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

by robot class we can perform CTRL + V operation as below :-
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);



by robot class we can press enter key as below :-
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);

Here is sample code :-

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Uploadfile
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\cchauhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
/*FirefoxOptions foptions = new FirefoxOptions();
foptions.setCapability("marionette", false);
driver = new FirefoxDriver(foptions);*/
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com/p/this-webpage-is-designed-for-selenium.html");
Thread.sleep(3000);
}
@Test
public void h() throws AWTException
{
driver.findElement(By.xpath(".//*[@id='post-body-2064404811754288590']/form[1]/input[1]")).click();
Robot robot = new Robot();
robot.setAutoDelay(2000);
StringSelection ss = new StringSelection("C:\\Users\\cchauhan\\Desktop\\wallpaper.png");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
robot.setAutoDelay(2000);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
}



TAGS :-

How to perform control + c operation in selenium

How to upload a file in selenium

Example to upload a file in selenium

upload a file in selenium using robot class

upload a file in selenium using sendkeys methods

Thursday 28 June 2018

Find Duplicate Element in Array, Find count of duplicate element in array, remove duplicate element from array



Hello Friends,

In this article , we will learn , Three below things :-
1). How to Find Duplicate Element in array
2). How to find count of duplicate element in array.
3). How to remove duplicate element from array.
Note : It is very important tutorial for interview purpose.

Video :


It can be achieved by simple below algorithm :-
First create a collection.
now compare each element, within this collection
If collection have that element, than ignore else add this element to collection.

Below is Sample code :-


package Chandan_Java.Chandan_Java;
import java.util.*;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class PojorunExample
{
@Test
public void g()
{
int x[] = {2, 9 , 5, 2, 3, 5, 7, 9, 3, 2};
List<Integer> list = new ArrayList<Integer>();
list.add(x[0]);
for(int i =0; i<x.length; i++)
{
if(list.contains(x[i]))
{
}
else
{
list.add(x[i]);
}
}
for(int j = 0; j<list.size(); j++)
{
System.out.println(list.get(j));
}
}
}

OUTPUT :-

2
9
5
3
7





Another Way to Remove Duplicate Elements from an Array Using HashSet Class of Set Interface

public class PojorunExample
{
@Test
public void g()
{
int x[] = {2, 9 , 5, 2, 3, 5, 7, 9, 3, 2};
Set<Integer> hs = new HashSet<Integer>();
for(int i =0; i<x.length; i++)
{
hs.add(x[i]);
}
for(int z : hs)
{
System.out.println(z);
}
}
}
OUTPUT :-
2
9
5
3
7


Example to get Duplicate Emailement from an Array & Occurance of duplicate element using HashMap class of Map Interface

package Chandan_Java.Chandan_Java;

import java.util.*;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
public class JavaInterview
{
@Test
public void g()
{
int x[] = {2, 2, 9 , 5, 2, 3, 5, 7, 9, 3, 2};
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i =0; i<x.length; i++)
{
if(map.containsKey(x[i]))
{
int t = map.get(x[i]) + 1;
map.put(x[i], t);
}
else
{
map.put(x[i], 1);
}
}
System.out.println(map);
}
}

OUTPUT :-
{2=4, 3=2, 5=2, 7=1, 9=2}

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

public class Interviewtest
{
//find the duplicate elements in the array
int count;
public static void main(String args[])
{
int arr[] = {4, 2, 2, 4, 55, 6, 99, 55};
AtomicInteger count = new AtomicInteger(1);
Set newarray = new HashSet();
for(int i =0; i<arr.length; i++)
{
if(newarray.contains(arr[i]))
{
int x = count.getAndIncrement();
//System.out.println("Element"+ " " + arr[i] + " " + x);
}
else
{
newarray.add(arr[i]);
}
for(int j =i+1; j<arr.length; j++)
{
if(arr[i]==arr[j])
{
System.out.println("Duplicate element is:->" +" "+arr[i]);
}
}
}
System.out.println(newarray);
g();
h();
}
public static void g()
{
String arr[] = new String[]{"chandan", "adhiraj", "Tina", "Cathy", "chandan", "adhiraj"};
Set duplicate = new HashSet<>();
Set nonduplicate = new HashSet<>();
for(String srting : arr)
{
/*if(!nonduplicate.contains(srting))
{
nonduplicate.add(srting);
}
else
{
duplicate.add(srting);
}*/
if(nonduplicate.contains(srting))
{
duplicate.add(srting);
}
else
{
nonduplicate.add(srting);
}
}
System.out.println(duplicate);
System.out.println(nonduplicate);
}
public static void h()
{
int arr[] = {4, 2, 2, 4, 55, 6, 99, 55};
for(int i =0; i<arr.length; i++)
{
int t = 1;
for(int j =i+1; j<arr.length; j++)
{
if(arr[i]==arr[j])
{
t = t+1;
}
}
System.out.println("Element" + " " + arr[i] + " " + "occurs" + " " + t);
}
}
}

Monday 14 May 2018

How To Perform Right Click Action (Context Click) In Selenium


Hello Friends,

In this article , we will learn , how to perform right click of mouse & select option "Open Link in New Tab" and "Open Link in New Window" using selenium webdriver.

Video :


Open link in new Tab :
So we will take an easy scenario as below :
Launch the browser
Navigate to the URL
right click on any link
select the option "Open Link in New Tab"
switch to new tab & perform some operation
close the new tab & switch back to parent tab.

To achieve this we will write a simple code in TestNG.

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Opennewtab
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\cchauhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com");
Thread.sleep(3000);
}
@Test
public void h()
{
WebElement seleniumtutorial = driver.findElement(By.xpath(".//*[@id='post-body-751561208295527719']/center/div[1]/table/tbody/tr[1]/td[4]/a/img"));
Actions action = new Actions(driver);
action.contextClick(seleniumtutorial).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String windowhandler = driver.getWindowHandle();
ArrayList tabs2 = new ArrayList (driver.getWindowHandles());
System.out.println(tabs2.size());
driver.switchTo().window((String) tabs2.get(1));
String link = driver.findElement(By.xpath(".//*[@id='post-body-7737945062927568046']/table[1]/tbody/tr[1]/td[1]/h2/a")).getAttribute("href");
System.out.println(link);
driver.close();
driver.switchTo().window(windowhandler);
System.out.println("i am working fine");
}
}


Open link in new window :
Now again scenarios will be same but opeartion will be performed in new window instead of new tab :

Launch the browser
Navigate to the URL
right click on any link
select the option "Open Link in New window"
switch to new window & perform some operation.
close the new window & switch back to parent window.
To achieve this we will write a simple code in TestNG.

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class OpennewWindow
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\cchauhan\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com");
Thread.sleep(3000);
}
@Test
public void h() throws InterruptedException
{
WebElement seleniumtutorial = driver.findElement(By.xpath(".//*[@id='post-body-751561208295527719']/center/div[1]/table/tbody/tr[1]/td[4]/a/img"));
Actions action = new Actions(driver);
action.contextClick(seleniumtutorial).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
String windowhandler = driver.getWindowHandle();
ArrayList tabs2 = new ArrayList (driver.getWindowHandles());
System.out.println(tabs2.size());
driver.switchTo().window(tabs2.get(1));
String link = driver.findElement(By.xpath(".//*[@id='post-body-7737945062927568046']/table[1]/tbody/tr[1]/td[1]/h2/a")).getAttribute("href");
System.out.println(link);
Thread.sleep(3000);
driver.close();
driver.switchTo().window(windowhandler);
System.out.println("i am working fine");
}
}

Sunday 22 April 2018

Create WebDriver instance for multiple class in different ways


Hello friends,

In this article we will learn how to create WebDriver Instance multiple classes:

So, we will create a WebDriver instance in one class & call it in multiple class
we have achieve this by 2 ways
1).By using extends
2).By using Singleton class

To know about singleton class Click Here

For Video :- Click Here



Method :1By extends Keyword

Step :1Create a class & initialize your driver

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class MainDriver
{
public static WebDriver driver;
public static void createInstance()
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
}


Step :2Create an another class & extend above driver class

public class Testcase1 extends MainDriver
{
public static void url()
{
MainDriver.createInstance();
driver.navigate().to("http://www.way2testing.com");
}
}


Step :3Create an another class & extend above driver class

public class TestCase2 extends MainDriver
{
public static void getTitle()
{
System.out.println(driver.getTitle());
}
}


Step :4Create an another class & extend above driver class

import org.testng.annotations.Test;

public class Excution
{
@Test(priority = 0)
public void getUrl()
{
Testcase1.url();
}
@Test(priority = 1)
public void getTitle()
{
TestCase2.getTitle();
}
}


If you will run this Exeution class , you can see that with one WebDriver Instance(driver), you are able to perform your all task.

Method :2By Singleton Class

Step :1Create a Singleton class & initialize your driver

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SingletonDriver
{
public static WebDriver driver = null;
public static void Initiallize()
{
if(driver == null)
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
}
public static void close()
{
driver.close();
}
public static void quit()
{
driver.quit();
}
}



Step :2Create a class for your test cases & execute singleclass method

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Testcases
{
@BeforeTest
public void initializeDriver()
{
SingletonDriver.Initiallize();
}
@Test(priority = 0)
public void openurl()
{
SingletonDriver.driver.navigate().to("http://www.way2testing.com");
}
@Test(priority = 1)
public void getTitle()
{
System.out.println(SingletonDriver.driver.getTitle());
}
}



So, by using above methods, you can create a WebDriver Instanse(driver) and can use it in your multiple classes.
Thanks :)





Swap Two variable in Java


Hello friends,

In this article we will discuss about swap variable without using third variable:

For Video :- Click Here



public class Swap
{
int x = 10;
int y = 15;
public static void main(String args[])
{
Swap object = new Swap();
object.g();
}
public void g()
{
x = x+y;
y = x-y;
x = x-y;
System.out.println("After Swap Value of y : " + y);
System.out.println("After Swap Value of x : " + x);
}
}


output :
After Swap Value of y : 10
After Swap Value of x : 15

Code Explanation : Suppose we have two variable x, y and they have value 10, 15 respectively and we want to swap these two variables value.
HOW IT WOULD BE DONE ?
1). First , i will join these two variables value & store it in variable x.
Now the value of x is 25.
2). Now, we will minus the value of y(15) from this x(25).
we will get 10 & will store in variable y
3). Now the value on y is 10 & value of x is 25.
again we will minus this y value from & store it in variable x so value of variable of x will become 15.

Congratulation You have swapped the value of two variable without using third variable. :)





1. Write a program to swap two string without using any third string/variable

Answer :- First add both the string and store in a existing variable then use String method Substring to get the string


Below is program


public class PracticeA {

public static void main(String args[]) {

String x = "chandan";
String y = "singh";

System.out.println("Value of x: " +x + " , " + "Value of y :" + y + " ," +"before swapping");
x = x+y;

y = x.substring(0, x.length()-y.length());

x = x.substring(y.length());
System.out.println("Value of x: " +x + " , " + "Value of y :" + y + " ," +"after swapping");
}
}



Output :- Value of x: chandan, Value of y :singh ,before swapping Value of x: singh, Value of y :chandan ,after swapping

---------------------------------------------------------------------------




Tags :

Swap two variable without using third variable in Java

how two swap two variable in java without using third variable

Tuesday 13 March 2018

Map Interface in Java, What is HashMap in Java? HashMap vs HashTable



HashMap in java


Hi all, in this demo i will describe about HashMap in java.



Java HashMap is a hash table based implementation of Java’s Map interface.
A Map, is a collection of key-value pairs. It maps keys to values.

Map Interface.
public interface Map
An object that maps key to values. A map cannot contain duplicate keys;each key can map to at most one value.
This interface takes the place of the Disctionary class, which was a totally Abstract Class rather than an interface.

HashMap is important for selenium as well as for interview also.
hashMap is a Map based collection class that is used for storing Key & Value(associated with keys).
1).It is donated as HashMap.
2).Hashmap contains only unique elements.
3).Hashmap may have only one null key and multiple null values
4). Hashmap maintains no order.

Here is the example of HashMap in Java.


import java.util.HashMap;
import java.util.Map;
public class TestCsc2
{
public static void main(String args[])
{
Map<String, Integer> hmp = new HashMap<String, Integer>();
hmp.put(null, 6); //hash map can have one null key which will be stored at hashMap(0)
hmp.put("aaa", 1);
hmp.put("aaa", 5);
hmp.put("bbb", 2);
hmp.put("ccc", 3);
hmp.put("ddd", 4);
System.out.println(hmp);
}
}

Output :

{null=6, aaa=5, ccc=3, bbb=2, ddd=4}





Here is another example of HashMap in Java.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class hashmapdemo
{
public static void main(String args[])
{
hashmapdemo obj = new hashmapdemo();
obj.g();
}
public void g()
{
Map <String, Integer > record = new HashMap< String, Integer >();
record.put("Anjana", 26);
record.put("Silpi", 27);
record.put("Heena", 28);
record.put("Adhiraj", 29);
System.out.println(record.get("Heena"));
Set<String> keys = record.keySet();
for(String i : keys)
{
System.out.println(i + ":" +record.get(i));
}
}
}

Output :

28
Adhiraj:29
Anjana:26
Silpi:27
Heena:28


-------------------------------------------------------------------
Another example of hashmap :-

public class ConsTest
{
public static void main(String args[])
{
Map<Integer, String> map = new HashMap<Integer, String<();
map.put(10, "Chandan");
map.put(20, "Adhiraj");
map.put(30, "Anngraj");
System.out.println(map.get(10));
for(Map.Entry m : map.entrySet())
{
System.out.println(m.getKey()+ " " + m.getValue());
}
System.out.println("Printing the value using set");
Set<Integer> keys = map.keySet();
for(int i : keys)
{
System.out.println(i + " " + map.get(i));
}
}
}

Output :-

Chandan
20 Adhiraj
10 Chandan
30 Anngraj
Printing the value using set
20 Adhiraj
10 Chandan
30 Anngraj




TreeMap in Java

TreeMap is Red-Black tree based NavigableMap implementation. It is sorted according to the natural ordering of its keys.
TreeMap class implements Map interface similar to HashMap class.
The main difference between them is that HashMap is an unordered collection while TreeMap is sorted in the ascending order of its keys.
TreeMap is unsynchronized collection class which means it is not suitable for thread-safe operations until unless synchronized explicitly.

Here is the example of TreeMap in Java.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class hashmapdemo
{
public static void main(String args[])
{
hashmapdemo obj = new hashmapdemo();
obj.g();
}
public void g()
{
//Map<String, Integer> record = new HashMap<String, Integer>();
TreeMap<Integer, String> record = new TreeMap<String, Integer>();
record.put(26, "Anjana");
record.put(28, "Heena");
record.put( 29, "Adhiraj");
record.put(27, "Silpi");
System.out.println(record.get(28));
for(Integer i : record.keySet())
{
System.out.println(i + ":" +record.get(i));
}
}
}


Output :

Heena
26:Anjana
27:Silpi
28:Heena
29:Adhiraj

-------------------------------------------------------------------
Another example of Treemap :-



public class ConsTest
{
public static void main(String args[])
{
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(10, "Chandan");
map.put(20, "Adhiraj");
map.put(30, "Anngraj");
System.out.println(map.get(10));
for(Map.Entry m : map.entrySet())
{
System.out.println(m.getKey()+ " " + m.getValue());
}
System.out.println("Printing the value using set");
Set<Integer> keys = map.keySet();
for(int i : keys)
{
System.out.println(i + " " + map.get(i));
}
}
}

Output :-

Chandan
10 Chandan
20 Adhiraj
30 Anngraj
Printing the value using set
10 Chandan
20 Adhiraj
30 Anngraj

HashMap vs TreeMap



HashMap vs HashTable vs SynchronizedHashMap vs ConcurrentHashMap



HashMap :- Not thread-safe, can have one null key & multiple null values.
Map<String, Integer>mp = new HashMap<String, Integer>();
// Map Interface is required to create object of HashMap class.

Hashtable :- Thread-safe, slow performance, null key and null values are not allowed.

SynchronizedMap :- Thread - safe, slow performance, one null key and multiple null values are allowed.
Collections.synchronizedMap(=new HashMap<String, Integer>());

ConcurrentHashMap :- Thread-safe, fast performance, null key and null values are not allowed.
ConcurrentHashMap<String, Integer> chm = new ConcurrentHashMap<String, Integer>();
//No Map interface is required to create the object of ConcurrentHashMap class.
//ConcurrenthashMap does not throw any ConcurrentModificationException.


Saturday 3 March 2018

for each loop in java with example



For each loop in Java with example

for Each loop in java :
Hi all, in this demo i will describe about for-each loop in java.

This loop is important for selenium as well as for interview also.
So as the name says when we want to perform some operation with each element of the list or collection or array, then we use this loop.
The Syntax of the loop is :
for(data_type variable_name : array|collection)
{
}
it will get more clear when we describe it through an example :

Example of for-each loop in java


public class foreach
{
public static void main(String args[])
{
int arr[] = {10, 20, 30, 44};
for(int x : arr)
{
System.out.println("Your number is :" + x);
}
}
}
---------------------------------------------------------------------------
Now, Suppose you are working in some selenium project, and have create a WebElement list then, you can perform operation with each element using for -each loop

For Each Loop in selenium Example :
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class foreach_selenium
{
WebDriver driver;
@BeforeTest
public void g() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\Complete selenium\\ChromeDriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("http://www.way2testing.com");
Thread.sleep(3000);
}
@Test
public void h()
{
List<WebElement >list = driver.findElements(By.cssSelector("#post-body-751561208295527719>div>div>table>tbody>tr>td>a"));
System.out.println("Your total list elements are :" +list.size());
for(WebElement wb : list)
{
System.out.println(wb.getText());
}
}
}




Output :

Manual Testings Introduction
Definitions of Manual Testings
Defect Clustering in Software Testing
Bug Life Cycle and Reviews
Level of Testing
TEST CASE, TEST PLAN and RTM
Manual test Cases for Pen
Manual test cases for Email
ISTQB Practice set
Important Unix Command for Software Tester
Testings Myth
Agile Methodology
Windows and Linux Shortcut keys
Test Strategy in Software Testing
Finance Testing Basics
Mobile Test
Effort Estimation Technique
Java Script Basics
How to test Login page & Date fields manually
Technical Tips
Function in Javascript
Discussion Forum
Download e_Books
Professional Ethics
Aptitude Tricks
English Speaking Tutorials

Wednesday 21 February 2018

Overview of Webservice




What is webservices ?


It's a simple xml based information exchange system, which uses internet for direct interaction between applications.

Watch Video


Components of webservice :
SOAP : Simple object access protocol
UDDI : Universal description and discovery integration.
WSDL :web services descriptive language.
Note : WSDL is a language , used by UDDI.
WSDL(Web Services Description Language)
WSDL is a language for describing web services and how to access them.
ESDL is written in xml.


What is SOAP ?
It is technology which allow communication between different languages. It allow us to pass the data over the internet in easy way.

A simple definition :
SOAP stands for Simple Object Access Protocol.
SOAP can interact with other programming language applications.
It is a just protocol which is XML Based for accessing web services over the internet.
It is recommended by W3C for communication between two application over the network.

Feature of SOAP :
1).It is a communication protocol designed to communicate via internet.
2).It can extend HTTP fro XML messaging.
3).It provide data transport for web services.
4).It can exchange complete documents or call a remote procedure.
5).It can be used for broadcasting a message.
6).It is both platform and language independent.
7).It is the XML way of defining what information is sent and how.
8).It enables the client applications to easily connect to remote services and invoke remote methods.


What is SOAP Message ?
SOAP Messages are just like post-box letter, in letter we have english text and in SOAP message we have XML.
As post-box have envelope, address, message, sender details etc. same in SOAP it have envelope, header, body & fault.

A SOAP message is an ordinary XML document containing the following elements −
Envelope − Defines the start and the end of the message. It is a mandatory element.
Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element.
Body − Contains the XML data comprising the message being sent. It is a mandatory element.
Fault − An optional Fault element that provides information about errors that occur while processing the message.

SOAP Message Structure

What is WSDL ?

WSDL : Stands for Web Service Description Language
1).It is a bese file which is used to describr web service and how to access them.
2).It is written in XML
3).WSDL is the document in XML. Which describe the webservice, the location of that webservice and operations exposed by webservices.
4).WSDL is written in simple XML.


Example of WSDL:-

Click Here or open below link in your browser
http://www.webservicex.com/globalweather.asmx?WSDL

WSDL have following major elements :-


type :Describe the data type used by webservices.
message :Messages used by web services.
porttype :Operation performed by web service.
binding :Communication protocols used in web service.

Advantage of SOAP :
SOAP has its own security known as WS Security.
Language and platform independent.
Disadvantage of SOAP :
It support only XML format, it has many standards which we have to follow while working with SOAP UI so that the reason it is slow.
It works with WSDL file onle so we can not use other format like JSON, header , Cookies and so on.



What is REST ?
RESTFUL WEB SERVICES :
REST stands for Representational State Transfer

It is platform dependent
It support multiple format like Json, HTML, XML, Plain text file too.
It is fast as compared to SOAP.
It is not a protocol like SOAP it is just a architectural design.



How WebServices works ?


A web service enables communication among various applications by using open standards such as HTML, XML, WSDL, and SOAP.
A web service takes the help of −
XML to tag the data
SOAP to transfer a message
WSDL to describe the availability of service.

OR In another way
Used XML for tagging >> Transfer it to SOAP >> WSDL to get the availabilities of services.

A simple definition: A web service is a function that can be accessed by other programs over the web (Http). To clarify a bit, when you create a website in PHP that outputs HTML its target is the browser and by extension the human being reading the page in the browser. A web service is not targeted at humans but rather at other programs.


Example: I can go to maps.google.com, and type in my home address, and see a map of where I live in my browser.
But what if you were writing a computer program where you wanted to take an address and show a pretty map, just like Google maps?
Well, you could write a whole new mapping program from scratch, OR you could call a web service that Google maps provides, send it the address, and it will return a graphical map of the location, which you can display in your program.

API vs WebService

API and web service both used for communication.
The only difference is that a Web service facilitates interaction between two machines over a network. An API acts as an interface between two different applications so that they can communicate with each other. An API is a method by which the third-party vendors can write programs that interface easily with other programs.

Summary:

1. All Web services are APIs but all APIs are not Web services. as all tigers are cats but not all cats are tiger

2. Web services might not perform all the operations that an API would perform.

3. A Web service uses only three styles of use: SOAP, REST and XML-RPC for communication whereas API may use any style for communication.

4. A Web service always needs a network for its operation whereas an API doesn’t need a network for its operation.

SOAP Vs REST


SOAP is Simple Object Access Protocol
Request and Response > XML Format
Uses Web Services and more secure.

SOAP
REST
SOAP is a ProtocolREST is an architechtral style
SOAP can not use REST beacuse it is a protocolREST can use SOAP web service because it is a concept and can use any protocol like HTTP, SOAP
SOAP uses services interfaces to expose the business logicREST uses URI to expose business logic
SOAP defines standars to be strictly followedREST does not define too much standard like SOAP
SOAP Requires more bandwidth and resource than RESTREST requires less bandwidth and resource than SOAP
SOAP defines its own securityRESTful web services inherits security measures from the underlying transport
SOAP permits XML data format onlyREST permits different data format such as Plain text, HTML,XML, JSON etc.



Representational State Transfer,
Each URI is representational of some object.
Uses Http get/post/put/delete and uses XML/json/html format
Totally stateless and light weight than soap
Not a protocol rather a architechtural style.



Advantange of REST Services over SOAP Services :

1).Rest Services are light weighted
Means less data transfer between client and server machine, ultimately need less bandwidth and fast.
in non-technical word : SOAP is just like post-office letter/courier where REST is just like post-card.

2).In case of SOAP Service, we can access complete application by using WSDL but in case of REST we can access only 1 functionality(Resource) by using URI, no need to access complete application.
Advantange for service provider is that they can sell complete application as well as only part of application, it will bring more small customer to it.

3).Soap Support only XML format for data exchange. Rest support HTML, XML, JSON , plain text, PDF etc.

4).SOAP service mainly support GET but Restful services uses for main HTTP methods :
a).GET to retrieve resource
b).POST to create resource
c).PUT to update resource
d).Delete to delete resource

5).SOAP defines standards(W3C) to be strictly followed(Which will take more time to develop, test and use) but REST does not define too much standards like SOAP.

What is URI ?

URI : Uniform Resource Identifier
Identifyng documents using a short of numbers, letters and symbol.


URL and URN A URN(Uniform Resource Name) ia an internet resource with a name.

Example of URI :
http://www.thomas-bayer.com/sqlrest/CUSTOMER
http://www.thomas-bayer.com/sqlrest/CUSTOMER/2
http://www.thomas-bayer.com/sqlrest/CUSTOMER/3

WSDL Vs WADL

WSDL : The web service description language(WSDL) is an XML vocabulary used to describe SOAP-based web services.
WSDL files that we will be using for SOAP based web services only.
It's major elements are :
Definition : root element of all WSDL documents, It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here.
Datatype : The data types to be used in the messages are in the form of XML schemas.
Message : It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation.
Binding : It is the concrete protocol and data formats for the operations and messages defined for a particular port type.
Operation : It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message.
Port : It is a combination of a binding and a network address, providing the target address of the service communication.
Service : It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions.



WADL : The web application descrition language(WADL) is an XML vocabulary used to describe RESTful web services and XML vocabulary for expressing the behaviour of HTTP resources.
main porpose to define the contact.


What is SOAP UI?


Soap UI is an open-source tool used for functional and non-functional testing,widely used in web-services testing.


SOAP UI important feature


1).It is capable of performing the role of both client and service.
2).It enables the users to create functional and non-functional tests quickly and in an efficient manner using a single environment.
3).It is licensed under the terms of the GNU Leaser General Public Licence.
4).It is purely implemented wing JAVA platform.
5).It supports Windows, Mac, multiple Linux dialects.
6).It allows testers to execute automate functional, regression, compliance and load tests on different WEb API.
7).It supports all the standard protocol and technologies to test all kind of APIs.

1).Soap UI is a tool from Samrtbear mainly for functional testing but it can also be used for non functional testing like performance, security of web services.

2).Web services can be created either by SOAP or REST method, we can work with both.

3).There are two version of SOAP UI in market :
SOAP-UI free
SOAP-UI Pro paid.

WebService

1). Webservice is the type of application or software component which does not provide any GUI for user to interact.

2). We can interact that kind of application passing input to specified XML format and receiving result in XML.

3). Webservive use HTTP protocol to communicate wth web service.

4).Web services are powered by XML and thee other core technologies: WSDl, SOAP and UDDI.

Type of WebService


SOAP Services (WSDL File)
REST Services (WADL File, URI)


Demo Soap Services
http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL

WorkSpace

1).In Soap UI first we need to create a workspace.
2).Workspace is a place where all our projects will be saved.
3).Workspace is a single XML file, we have multiple projects in a sigle workspace.
4).It is Simillar like Domain, we can have multiple projects in a single domain.



How to download and install the SOAP UI


navigate to below url :
https://www.soapui.org/downloads/soapui.html
or click here

Click here to download from drive







Tuesday 20 February 2018

HTTP Request and HTTP Response

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-6658533981545355", enable_page_level_ads: true }); </script>


Hello Friends,

Before starting the API Testing a tester must know what is HTTP Request and HTTP response, so this article mainly cover :
HTTP Request
HTTP Response

The HTTP Protocol :

HTTP : Hypertext Transfer Protocol

The HTTP is an application layer protocol(OSI Model) that allows web-based applications to communicate and exchange data.


OSI Layers are as below:
Application
Presentation Session
Transport
Network
Data Link
Physical

OSI model in detailed view :





What is HTTP?


The HTTP is the messenger of the web
It is a TCP/IP based protocol
It is used to deliver content for example images, videos, audios, documents etc.
The computer that communicate via the HTTP must speak the http protocol



Three Important things about HTTP


1). HTTP is connectionless means after making the request, the client disconnect from the server, then when the response is ready the server re-establish the connection again and deliver the response.
2). The HTTP can deliver any sort of data, as long as the two computers are able to read it.
3). The HTTP is a stateless means the client and server know about each other just during the current request, it is closes and the two computers want to connect again, they need to provide information to each other anew, and the connection is handled as the very first one.

Key points :


1).The HTTP is a TCP/IP based application layer protocol that allows web based applications to communicate and exchange data.
2).The computers that communicate via the HTTP must speak the http protocol.
3). The http is stateless, connectionless and can deliver any data.
4).We use the http protocol bacause it is a convenient way to quickly and reliably move data on the web.
5). The request response cycle works on the web via http messages.
6). A http message contains three sections the start line, the header and the body.
7).The http request message differs from the http response messages.


Cycle of HTTP Request & Response





HTTP Request :

An HTTP client sends an HTTP request to a server and basically this request is a packet of information.
This packet ave binary data sent by the client to the server.


HTTP Request contains following three things :


1). Request Line
2). zero or more header (General|Request|Entity) fields followed by CRLF
and an empty line(i.e. a line with nothing preceding the CRLF)
indicating the end of header fieds
3). Message body of request (Optionally)



Two HTTP Request Methods:

GET and POST

Two commonly used methods for a request-response between a client and server are: GET and POST.
GET - Requests data from a specified resource
POST - Submits data to be processed to a specified resource



Request line have Request Method, Request URI, HTTP Protocol

Request Header : In the request section, whatever follows Request Line till before Request Body everything is a Header.
Headers are used to pass additional information about the request to the server.

Request Body is the part of the HTTP Request where additional content can be sent to the server.
For example, a file type of JSON or XML.


Let's better understand by below Image :




HTTP Response :


After successfully receiving and interpreting a request message, server responds with a HTTP response message.
This response is the packet of information sent by server to the client.
As like HTTP Request, HTTP Response also have three things :

1).A status Line
2).Zero or more header (Genreal|Response|Entity) fields followed by CRLF
An empty line (i.e. a line with nothing preceding the CRLF)
indicating the end of the header fields
3). Message Body (optionally)


Status line has , HTTP Protocol version, Status code like 200, and Status message as OK,
Response header, Response Header also contains zero or more Header lines. However, it is very uncommon to have zero Headers in the response. Lines just after the Status Line and before the Response Body are all Response Headers lines.
Response Body , Response Body contains the resource data that was requested by the client.
Note: Response Body contains text in JSON format, as one of the Response headers suggested.
can better understood by below image :




HTTP Staus code :


1xx Informational response :
100 Continue
101 Switching Protocol
102 Processing
103 Early Hints

2xx Success :
200 OK
201 Created
202 Accepted
203 Non-Autoritative Information
204 No Content
205 Reset Content
206 Partial Content
207 Multi-Status
208 Already Reorted
226 IM Used

3xx Redirection :
300 Multiple choices
301 Moved Permanently
302 Found
303 see other
304 Not Modified
305 Use Proxy
306 Switch Proxy
307 Temporary Redirect
308 Permanent Redirect

4xx Client errors :
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Payload Too Large
414 URI Too Long
415 Unsupported Media Type
416 Range Not Satisfiable
417 Expectation Failed
418 I'm a teapot
421 Misdirected Request
422 Unprocessable Entity
423 Locked
424 Failed Dependency
426 Upgrade Required
428 Precondition Required
429 Too Many Requests
431 Request Header Fields Too Large
451 Unavailable For Legal Reasons

5xx Server errors :
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
506 Variant Also Negotiates
507 Insufficient Storage
508 Loop Detected
510 Not Extended
511 Network Authentication Required

Click here for next topic

click here for previous topic