Thursday, August 27, 2015

Java : Generics

Generics



If you declare a method to take ArrayList<Animal> it can take ONLY an ArrayList<Animal>, not ArrayList<Dog> .To avoid this we use generics :

 ie.,Use ArrayList<? extends Animal> instead of ArrayList<Animal> 

(Animal is parent class)

Note : But this is not required if user is sending arrays[],


Example :

public class generics {

    public static void main(String[] args) {
       
        ArrayList<Animal> A=new ArrayList<Animal>();
        A.add(new Animal());

        ArrayList<dog> B=new ArrayList<dog>();
        B.add(new dog());
        B.add(new dog());

        System.out.println(new generics().cal(B));
        System.out.println(new generics().cal(A));
    }
       
//    try ArrayList<Animal>-------instead of-------- ArrayList<? extends Animal>
    public int cal( ArrayList<? extends Animal> A ){       
        return A.size();
    }
}

class Animal{
    private boolean wild;

    public void set_wild(boolean wild){
        this.wild=wild;
    }
   
    public boolean get_wild(){
        return this.wild;
    }   
}

class dog extends Animal{
   
    private StringBuffer dog_name=new StringBuffer();
   
    public void set_dogname(String dog_name){
        this.dog_name.append(dog_name);
    }
}


Output (ArrayList<? extends Animal>) :
1
2

Output (ArrayList<Animal>)
Error

Monday, August 24, 2015

Selenium : Writing Test Results in Excel - Part 2

Writing Test Results in Excel - Part 2









Example

Test 1 (launchSiteAndLogin)
    1. Go to http://www.seleniummaster.com/seleniummastertestapp/index.php
    2. Enter "test" in the Username field
    3. Enter "XXXX" in the Password filed
    4. Click on the Login button
    5. Verify that the text "Selenium Test" is present.

Test 2 (ChangeUserSettings)
    1. Click on the radio button near friends need my authorization to add me
    2. Click on the save button
    3. Verify that the text "preference saved" displayed.

Test3 (Logout)
    1. Click on the Logout button
    2. Verify that Login button displayed.


Pre-req :

1. TestNg
2. ApachePOI libaray

   

Step 1: write the UserSettingTest.java code as follows

public class UserSettingTest
{
private WebDriver browser;
private String baseUrl;
HSSFWorkbook workbook;
HSSFSheet sheet;
Map<String, Object[]> testresultdata;//define a test result data object
@BeforeClass(alwaysRun = true)
public void setupBeforeSuite(ITestContext context) {
baseUrl = "http://www.seleniummaster.com";
workbook = new HSSFWorkbook();
sheet = workbook.createSheet("Test Result");
testresultdata = new LinkedHashMap<String, Object[]>();
testresultdata.put("1", new Object[] {"Test Step Id", "Action", "Expected Result","Actual Result"});
try {
browser=new FirefoxDriver();
browser.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} catch (Exception e) {
throw new IllegalStateException("Can't start Web Driver", e);
}
}
@Test(description="Launches the Selenium Master Test Application and Login")
public void launchSiteAndLogin() throws InterruptedException{
browser.get(baseUrl+"/seleniummastertestapp/index.php");
browser.findElement(By.id("login_login_username")).sendKeys("test");
browser.findElement(By.id("login_login_password")).sendKeys("XXXXX"); //password is omitted
browser.findElement(By.id("login_submit")).click();
try{
assertEquals(browser.findElement(By.id("id1")).getText(),"Test Selenium");
//add pass entry to the excel sheet
testresultdata.put("2", new Object[] {1d, "navigate to site and login", "site opens and login success","Pass"});
}
catch(Exception e)
{
//add fail entry to the excel sheet
testresultdata.put("2", new Object[] {1d, "navigate to site and login", "site opens and login success","Fail"});
}
}
@Test(description="Change a User settings to add as a friends after authorization")
public void ChangeUserSettings() {
browser.findElement(By.xpath("//input[@value='auth']")).click();
browser.findElement(By.id("accountprefs_submit")).click();
try{
assertEquals(browser.findElement(By.cssSelector("div.ok")).getText(), "Preferences saved");
//add pass entry to the excel sheet
testresultdata.put("3", new Object[] {2d, "User can change settings", "Settings changed","Pass"});
}
catch(Exception e)
{
//add fail entry to the excel sheet
testresultdata.put("3", new Object[] {2d, "User can change settings", "Settings NOT changed","Fail"});
}
}
@Test(description="Log out the system")
public void Logout() throws InterruptedException {
browser.findElement(By.linkText("Logout")).click();
try{
assertTrue(isElementPresent(By.id("login_login_username")));
//add pass entry to the excel sheet
testresultdata.put("4", new Object[] {3d, "User can logout", "Logout successfull","Pass"});
}
catch(Exception e)
{
//add fail entry to the excel sheet
testresultdata.put("4", new Object[] {3d, "User can logout", "Logout successfull","Fail"});
}
}
@AfterClass
public void setupAfterSuite() {
//write excel file and file name is TestResult.xls
Set<String> keyset = testresultdata.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = testresultdata.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}
try {
FileOutputStream out =new FileOutputStream(new File("TestResult.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//close the browser
browser.close();
browser.quit();
}
private boolean isElementPresent(By by) {
try {
browser.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}


Step 3: Create a testng.xml file to run the test suite as TestNG Suite.
Step 4: Right click on the testng.xml file and select run as TestNG Suite.
Step 5: Check the test result on the console or in the test-output folder. Generally, open the index.html under the test-output folder to view the result.

The result file indicated that all the tests passed. With this pattern, you can expand the test suite with many test modules.You can also see the TestResult.xls file to view the test result. When you open the excel file, you will see the test result as shown below.

TestStepId    Action                                   Expected Result                      Actual Result
1                   navigate to site and login     site opens and login success     Pass
2                   User can change settings     Settings changed                      Pass
3                   User can logout                    Logout successfull                   Pass



Selenium : Writing Test Results in Excel - Part 1


Writing Test Results in Excel - Part 1




Pre-Req :

1. TestNG is required.
2. Download the Jar from here ExcelReportGenerator . Add this Jar into your project BuildPath.

Steps Below:

Step1 : Create a Package ‘ExcelResults’ under your Project.

Step2 : Create  the testcases which you’d like to automate using TestNg. (by using @Test,BeforeTest,…….) as Shown.


public class Test
{
static WebDriver driver;
@Test(priority = 1)
public static void validatingDollarTest1() {
System.out.println(this is validating the DollarTest1”);
}
@Test(priority = 2)
public static void ValidatingDollarTest2() {
System.out.println(this is validating the DollarTest2”);
}
@Test(priority = 3)
public static void validatingDollarTest3() {
System.out.println(this is validating the DollarTest3”);
}
}

Step3 : Create a testng.xml file under your Project as Shown.

  <?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd”&gt;
<suite name=”Random test suite” >
<test name=”EnterYourTestName”>
<classes>
<class name=”Test_98″/>
</classes>
</test>
</suite>

Now Run the testng.xml file.

Step 4 : Now Create a Class ‘ExcelGenerate’  and paste the following code.


import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.raybiztech.commonexcelreport.ExcelReportGenerator;

public class ExcelGenerate
{
public static void main(String[]args) throws ParserConfigurationException, IOException, SAXException
{
ExcelReportGenerator exe= new ExcelReportGenerator();
exe.GenerateExcelReport(YourTestName.xls);
}
}

Step5 :Refresh the Package ‘ExcelResults’


Now you see the excelReport Generated. Its so simple huh !!!

*If you see the columns in the excel were disturbed please change the settings or Use the latest Version. I have made this using  ‘Libre’.

Tuesday, August 18, 2015

Java : Collections Sort

Collections Sort


To sort a given Array List in Ascending order :

1) Standard Sort : For String Type
2)Custom Sort : For Object Type


Standard Sort

public class sorting {
    public static void main(String[] args) {
       
        ArrayList<String> places=new ArrayList<String>();
       
        places.add("bangalore");
        places.add("delhi");
        places.add("Agra");
       
        System.out.println(places);
       
        Collections.sort(places);
        System.out.println(places); //Arrange in Ascending order
       
    }
}



Output:
bangalore,delhi,Agra
Agra,bangalore,delhi

Improved Sort


public class improved_sort {

    public static void main(String[] args) {
        new test2().start_now();
    }
}



//Getter Setter Class
class Student implements Comparable<Student>{
   
    private String name;


       public void set_name(String name){
        this.name=name;
    }
   
    public String get_name(){
        return name;
    }

    public int compareTo(Student o) {
        return name.compareTo(o.name);
    }  
 
}

class test2{
   
    public void start_now(){
      
        ArrayList<Student> students=new ArrayList<Student>();
        Student s1=new Student();
        Student s2=new Student();
        Student s3=new Student();
      
        s1.set_name("rahul");
        s2.set_name("pahul");
        s3.set_name("mahul");
      
        students.add(s1);
        students.add(s2);
        students.add(s3);
      
        for(Student s:students)
            System.out.print(s.get_name());
      
        Collections.sort(students);
      
        System.out.print("\n");
      
        for(Student s:students)
            System.out.print(s.get_name());
    }
   }


OutPut :
rahulpahulmahul
mahulpahulrahul

Custom Sort :

public class custom_sort {
    public static void main(String[] args) {
        testing Test=new testing();
        Test.start();
    }
}

//Getter , Setter Class to create Animal Object 
class Animal{
  
    private String Animal_type;
  
    public void set_Animaltype(String Animal_type){
        this.Animal_type=Animal_type;      
    }
  
    public String get_Animaltype(){
        return Animal_type;
    }  
}


class testing{
  
    public void start(){
        ArrayList<Animal> animals=new ArrayList<Animal>();
        Animal dog=new Animal();
        dog.set_Animaltype("dog");
      
        Animal cat=new Animal();
        cat.set_Animaltype("cat");
      
        Animal ant=new Animal();
        ant.set_Animaltype("ant");
              
        animals.add(dog);
        animals.add(cat);
        animals.add(ant);
      
        System.out.print("Before  Sorting = ");
        for (Animal str:animals)
            System.out.print(" "+str.get_Animaltype());
      
        custom_sort sort_logic=new custom_sort();      
        Collections.sort(animals, sort_logic); //
          
        System.out.print("\nAfter  Sorting = ");
        for (Animal str:animals)
            System.out.print(" "+str.get_Animaltype());
                  
    }
  
//inner class
    class custom_sort implements Comparator<Animal>{
        public int compare(Animal o1, Animal o2) {
            return o1.get_Animaltype().compareTo(o2.get_Animaltype());
        }    
    }
  
}


 OutPut
Before  Sorting =  dog cat ant
After  Sorting =  ant cat dog

Monday, August 3, 2015

Java :Reflection

Reflection


public class reflection_test
 {
    public static void main(String[] args)

 {
        ArrayList<Object> obj =new  ArrayList<Object>();
        obj.add("hi"); //passing String
        obj.add(123);    //Passing int
        reflection_class.Caller_method("method2",obj);
    }
}


class reflection_class

{
//    reflection_class rc_instance=new reflection_class();
//    Class rc_Class=rc_instance.getClass();
   
    public static void Caller_method (String method_name,ArrayList<Object> parameters)

{
//Method m=rc_Class.getMethod("method1", ArrayList.class );
            Method m=reflection_class.class.getMethod(method_name, ArrayList.class);

//getdeclaredmethod can also be used

            m.invoke(method_name, parameters);
            }       
   
    public static void method1(ArrayList<Object> parameters)
    {
        System.out.println("method1: "+parameters.get(0));
        System.out.println("method1: "+parameters.get(1));
    }
   
    public static  void method2(ArrayList<Object> parameters)
    {
        System.out.println("method2:"+parameters.get(0));
    }   
}

Java :HashTable Vs Dictionary Vs Hashmap

HashTable Vs Dictionary VsHashMap

Dictionary is an abstract class, superclass of Hashtable. You should not use Dictionary as it is obsolete. As for Hashtable, the advantage it had over other maps such as HashMap was thread safety, but with the introduction of ConcurrentHashMap since Java 1.5, there is no real reason to use it any longer.

 Dictionary is an abstract class in Java whereas Map is an interface. Since, Java does not support multiple inheritances, if a class extends Dictionary, it cannot extend any other class.Therefore, the Map interface was introduced.Dictionary class is obsolete and use of Map is preferred.

In summary: Don't use Dictionary or Hashtable, unless you really have to for compatibility reasons, use either HashMap if you don't need thread safety, or ConcurrentHashMap if your map is used in a concurrent environment.

 

Example:

 HashMap<String, String> hash_map = new HashMap<String, String>();

        hash_map.put("name1", "john");
        hash_map.put("name2", "marry");
        System.out.println(hash_map);

        System.out.println("name2= "+hash_map.get("marry"));
        System.out.println("Is HashMap empty? "+hash_map.isEmpty());
        hash_map.remove("name1");
      
        System.out.println(hash_map);
        System.out.println("Size of the HashMap: "+hash_map.size());


    

Output   
        {name1=john, name2=marry}
        name2= marry
        Is HashMap empty? false
        {name2=marry}
        Size of the HashMap: 1
        

 

 

Java :Lists Vs ArrayLists

Lists Vs ArrayLists

List<?> myList = new ArrayList<?>();

ArrayList<?> myList = new ArrayList<?>();


  • List is an interface and ArrayList is an implementation of the List interface.
  • There is no much of a difference except for the basic polymorphism concept that if you use Lists then you will only able to use methods of only Lists type but if you use ArrayList you should be able to use methods from ArrayList as well as from Lists and Overridden methods by ArrayLists if any.
  •  List can change (to a LinkedList for example), without affecting the rest of the code. This will be a difficult task to do with an ArrayList, not only because you will need to change ArrayList to LinkedList everywhere, but also because you may have used ArrayList specific methods.

Wednesday, July 29, 2015

Java : String Vs StringBuffer vs StringBuilder

Java : String Vs StringBuffer vs StringBuilder 

 

So suppose you declare a String object:
String myString = “Hello”;

Next, you want to append “Guest” to the same String. What do you do?
myString = myString + ” Guest”;

Result : “Hello Guest”.

Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.


Example :
        String s = "Let’s test";
        s.concat("if this works then the string is IMMUTABLE");
        System.out.println(s);
      
        s = s.concat("if the String object is not IMMUTABLE");
        System.out.println(s);

To Make String Operations more Efficient ?

Ans : By using StringBuffer/StringBuilder

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized ie., multiThreading is possible in StringBuffer  , hence slower compared to StringBuilder.

Example :
StringBuffer st=new StringBuffer("ahsas");
st.append("123");
st.append(123);



Monday, July 20, 2015

Browsers : Download Chrome and FireFox Versions


Download Chrome and FireFox Versions


http://ftp.mozilla.org/pub/mozilla.org/firefox/releases/

http://ftp.freenet.de/pub/filepilot/fpt/internet/browser/



Friday, June 12, 2015

Java : Excellent Interface Example

 Excellent Interface Example


//Using interface user need not have to think about child parent relation
//any class which implements an interface, can be assigned to that implementing interface instance variable

//Ex: Itree= Interface
//Apple and mango class implements Itree
//Once implemented , I can Use Interface variable to reference both apple and mango
//Also use Interface Array List for looping the same

//Note : Even when there is a new tree ,ex:Strawberry , I can just create a strawberry class implementing Itree and add it to Itree_ArrayList
//this way the code changes is very minimal and I dont need to touch other code.


interface Itree{
public void fruit();
}

class apple implements Itree{
public void fruit() { System.out.println("apple"); }
public void children(){System.out.println("apple a day keeps doctor away"); }
}

class mango implements Itree{
public void fruit() {System.out.println("mango"); }
}




public class tree {
public static void main(String[] args){
ArrayList<Itree> Itree_ArrayList=new ArrayList<Itree>(); // Itree_ArrayList = Interface Array List
Itree tree1=new apple();
Itree tree2=new mango();
Itree_ArrayList.add(tree1);
Itree_ArrayList.add(tree2);
for(Itree t_count:Itree_ArrayList)
t_count.fruit();
apple app=(apple)Itree_ArrayList.get(0);//user can access other methods by casting to apple varibale
app.children();
}
}


Output :
 apple
mango
apple a day keeps doctor away


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

I think it works best for me to create Util library s.But only downside is Static variables are considered to be final.In this case use cannot create getter methods to  change the value of i

public class tree {
public static void main(String[] args){
Itree.static_method();
}
}

interface Itree{
static String i="";
public static void static_method(){ System.out.print("hi"); }
}

Output :
hi 

Monday, May 11, 2015

Java : Sorting ArrayList

Sorting ArrayList


Ref :how-to-sort-an-arraylist-in-java

import java.util.ArrayList;
import java.util.Collections;
 
public class SortingArrayList {
 
    public static void main(String args[]){
 
       ArrayList<String> al = new ArrayList<String> ();
 
            al.add("22");
            al.add("33");
            al.add("11");
            al.add("cc");
            al.add("bb");
            al.add("aa");
 
            System.out.println("Printing List before sorting......");
             for(String value: al){
                 System.out.println(value);
             }
 
             //Sorting...
             Collections.sort(al);
 
             System.out.println("Printing List after sorting......");
             for(String value: al){
                System.out.println(value);
             }
}
}
 

Output

Printing List before sorting……
22
33
11
cc
bb
aa
Printing List after sorting……
11
22
33
aa
bb
cc