Friday, February 21, 2014

Android : Hide Title Bar and Making full screen

Hide Title Bar and Making full screen



CODE HERE :

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
     
    requestWindowFeature(Window.FEATURE_NO_TITLE);  

    //code that displays the content in full screen mode  


    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

     
    setContentView(R.layout.activity_main); 
   

Thursday, February 20, 2014

Android : Simple Application for Android


Simple Application in Android

Application which prints a message when the button is pressed :


Code Here

package com.example.sample;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {   
        Button oButton;
        TextView txt;
        String message="some data";
       
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           
                /*--------ABOVE IS AUTO CREATED BY PROJECT , CODE STARTS FROM HERE ---*/   
           
            oButton = (Button) findViewById(R.id.button1);
            oButton.setOnClickListener(new Button.OnClickListener() {
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Alert Dialog");
                    builder.setMessage("Welcome to Android Application");
                    builder.setPositiveButton("OK", null);
                    builder.show();
                }});

        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}















activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="108dp"
        android:text="@string/press_me" />
</RelativeLayout>







Android :Creating a Alert Message Box (Toast)

Creating a Alert Message Box

Code Here : 

               AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Alert Dialog");
                builder.setMessage("Welcome to Android Application");
                builder.setPositiveButton("OK", null);
                builder.show();




Code to Display Toast when OK button is pressed
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Alert Dialog");
                builder.setMessage("Welcome to Android Application");
               
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                     public void onClick(DialogInterface dialog,int which)
                     {
              Toast.makeText(getApplicationContext(),"You clicked on OK",   Toast.LENGTH_SHORT).show();        
                     }



example 2:

 Add a button to activity_main.xml

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button oButton=(Button)findViewById(R.id.button);
        oButton.setOnClickListener(
                new Button.OnClickListener(){
                    public void onClick(View v){
                        new misc().alert_box("hi","hi",MainActivity.this);
                    }
                }
        );
    }
} 
----------------------------------------- 
package com.example.dejayapr.test1;
import android.app.AlertDialog;
import android.content.Context;

class misc {

    public void alert_box(String title,String message,Context c){
        AlertDialog alertDialog = new AlertDialog.Builder(c).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.show();
    }
} 
-----------
 

Java : Add Action Listener for GUI

Android : Action listener for button


Action listener for button in Android


Code Below


Button buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
            //Do stuff here
    }
});

Monday, February 17, 2014

Java : Add Browse button to GUI

Add Browse button to GUI

 

 Before starting :

  1. WindowBuilder Pro - should have been added to eclipse
  2. Create a new project
  3. Inside your package  , Rt ck >New >Other>WindowBuilder-Swing Designer-(Select) Application window.
  4. Once the workspace is created , at the bottom a new tab "Design" will be created. Select that.
  5. Now in the Layout select "Spring Layout" or "Mig Layout"  - this would place the relative and child properties close .
  6. Now in  components > click JButton and click on UI panel where you want it to be placed.
  7. Now right click on the placed element and select Add>Event handler>Mouse >Mouse clicked.
  8. Once done you will be taken to the code, an Anonymous class will be created on JButton.
  9. Come back to design .
  10. In components >select JFile Chooser and place it on the panel.
  11. Once done go back to the source and find JFile Chooser code and put it inside the anonymous inner class of JButton created before.
  12. Now add JFileChoose_object.showOpenDialog(class_name.this);
  13. Now run the same

 

Code Here :

JButton btnBrowse = new JButton("Browse");
        btnBrowse.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser Filechoose=new JFileChooser();
                int retval=Filechoose.showOpenDialog(GUI2.this);

                if (retval == JFileChooser.APPROVE_OPTION) {
                    //... The user selected a file, get it, use it.
                    File file = Filechoose.getSelectedFile();
                    System.out.println(file.getPath());
                }
            }
        });

Java : GUI Design

 GUI Design in Eclipse using Window Builder Pro


Steps below : 
  1.  Open Eclipse 
  2. Open Webpage "https://www.eclipse.org/windowbuilder/download.php"
  3. Click on the suitable link depending on the version of Eclipse.
  4. Once the page has opened >Copy the URL of the new page
  5. Goto Eclipse > Help >Install New Software >  and paste it in "work with" field  
  6. Click on next 

Friday, February 14, 2014

Selenium : Compare 2 images and give percentage similarity

 Compare 2 images and give percentage similarity


visit here: http://www.cse.iitk.ac.in/users/abhik/pixel.java


CODE HERE :

//THIS IS THE SOURCE CODE FOR PIXEL WISE COMPARISON OF TWO IMAGES AND SHOWING PERCENTAGE SIMILARITY.

import java.io.*;
import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
class spe
{
  public static void main(String args[]) throws IOException{
long start = System.currentTimeMillis();
    File file= new File("p1.png");
    BufferedImage image = ImageIO.read(file);
 int width = image.getWidth(null);
    int height = image.getHeight(null);
int[][] clr=  new int[width][height];
File files= new File("p2.png");
    BufferedImage images = ImageIO.read(files);
 int widthe = images.getWidth(null);
    int heighte = images.getHeight(null);
int[][] clre=  new int[widthe][heighte];
int smw=0;
int smh=0;
int p=0;
//CALUCLATING THE SMALLEST VALUE AMONG WIDTH AND HEIGHT
if(width>widthe){ smw =widthe;}
else {smw=width;}
if(height>heighte){smh=heighte;}
else {smh=height;}
//CHECKING NUMBER OF PIXELS SIMILARITY
for(int a=0;a<smw;a++){
for(int b=0;b<smh;b++){
clre[a][b]=images.getRGB(a,b);
clr[a][b]=image.getRGB(a,b);
if(clr[a][b]==clre[a][b]) {p=p+1;}
}}

float w,h=0;
if(width>widthe) {w=width;}
else {w=widthe;}
if(height>heighte){ h = height;}
else{h = heighte;}
float s = (smw*smh);
//CALUCLATING PERCENTAGE
float x =(100*p)/s;

System.out.println("THE PERCENTAGE SIMILARITY IS APPROXIMATELY ="+x+"%");
long stop = System.currentTimeMillis();
System.out.println("TIME TAKEN IS ="+(stop-start));
  }
}

Thursday, February 13, 2014

Selenium : TakeScreenshot of only Particular element

TakeScreenshot of only Particular element


CODE HERE :
 
/* sPath - Path where the screenshot needs to be saved
oElement - Element object contains the element which is under consideration    */

public static void element_screenshot(WebDriver driver,WebElement oElement,String sPath){
        try{
            File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            BufferedImage  fullImg = ImageIO.read(screenshot);
                    //Get the location of element on the page
            Point point = oElement.getLocation();
                    //Get width and height of the element
            int eleWidth = oElement.getSize().getWidth();
            int eleHeight = oElement.getSize().getHeight();
                    //Crop the entire page screenshot to get only element screenshot
            BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
            ImageIO.write(eleScreenshot, "png", screenshot);
                    //Copy the element screenshot to disk
            FileUtils.copyFile(screenshot, new File(sPath));
        }catch(Throwable t)
        {
            System.out.println("Webelement not found :"+t.getMessage());
        }            
    }

Friday, February 7, 2014

Selenium : Compare 2 Images in Java

Compare 2 Images in Java

CODE HERE  (Simple method to compare 2 images )


 public static boolean Compareimages(String file1,String file2) {
           
            try{
                    File file_1 = new File(file1);
                    File file_2 = new File(file2);
       
                    BufferedImage bufile_1 = ImageIO.read(file_1);
                    DataBuffer dafile_1 = bufile_1.getData().getDataBuffer();
                    int sizefile_1 = dafile_1.getSize();           
                   
                   
                    BufferedImage bufile_2 = ImageIO.read(file_2);
                    DataBuffer dafile_2 = bufile_2.getData().getDataBuffer();
                    int sizefile_2 = dafile_2.getSize();
                   
                    Boolean bFlag = true;
                    System.out.println(bFlag);
                    if(sizefile_1 == sizefile_2) {
                        System.out.println("Size match successfull");
                       for(int j=0; j<sizefile_1; j++) {
                             if(dafile_1.getElem(j) != dafile_2.getElem(j)) {
                                   bFlag = false;
                                   System.out.println("Image comparsion fail !!  :-(");
                                   break;
                             }
                        }
                    }
                    if (bFlag==true)
                        System.out.println("Image comparsion success !! :-) ");      
                        return bFlag;
                       
            }catch(Throwable t){
                    System.out.println("File not found\n"+t.getMessage());
                    Assert.assertTrue(false);
                    return false;
            }
           
        }
    

Wednesday, February 5, 2014

Selenium : Parallel Execution

Parallel Execution

 

In the below screen shot , there is Xml file with "parallel" command which creates threads =Number of tests <classes> <class> .

Here is the screen of the output
 xml file (Note xml file should be outside the package but inside the project meaning testng.xml file have only 1 parent ie., the project where it is placed )


Selenium :ClassNotFoundException: SaxonLiaison

ClassNotFoundException: SaxonLiaison


Error found while generating XSLT report , which requires - saxon.jar, SaxonLiaison.jar  files to be added  to your library.

 

Saxsion Error


Friday, January 31, 2014

Selenium: TestNG Error Reporting using IReporter (without halting)

 TestNG Error Reporting using IReporter (without halting)


1.Create a package inside your project.Ex:Reporter
2. Create a new Class CustomReporter  inside the package.
3. Copy the below code inside the Class as in the screenshot (Code below).


4. Goto your testng.xml file and add the following code as in the screenshot : 

5. My SampleTest file containing all the test Cases look like this .
6 . The result will look like this :







Code for - CustomReporter :

import java.util.List;
import java.util.Map;
import org.testng.IReporter;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;
import org.testng.xml.XmlSuite;

public class CustomReporter implements IReporter {

  @Override
  public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
  //Iterating over each suite included in the test
   for (ISuite suite : suites) {
     //Following code gets the suite name
     String suiteName = suite.getName();
     //Getting the results for the said suite
     Map<String, ISuiteResult> suiteResults = suite.getResults();
     for (ISuiteResult sr : suiteResults.values()) {
       ITestContext tc = sr.getTestContext();
       System.out.println("Passed tests for suite '" + suiteName +"' is:" + tc.getPassedTests().getAllResults().size());
       System.out.println("Failed tests for suite '" + suiteName +"' is:" + tc.getFailedTests().getAllResults().size());
       System.out.println("Skipped tests for suite '" + suiteName +"' is:" + tc.getSkippedTests().getAllResults().size());
     }
   }
  }
}

Selenium : TestNG error Reporting using IListener (without halt)

Selenium : TestNG error Reporting using IListener (without halt)


  1. Create a package in your project     Example: logger
  2. Create  a Class CustomLogging inside your package.
  3. Paste the below code as mentioned in the screenshot (code below) :

4.  Open your Testng.xml and add the following code as mentioned in the screen shot:

5. Screen shot of the "SampleTest" which contains my test cases.
6. Result when i run the code.



Code Here - CustomLogging :

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;


public class CustomLogging implements ITestListener{
  
  @Override //Called when the test-method execution starts  
  public void onTestStart(ITestResult result) {
    System.out.println("Test method started: "+ result.getName()+ " and time is: "+getCurrentTime());    
  }

  @Override //Called when the test-method execution is a success
  public void onTestSuccess(ITestResult result) {
    System.out.println("Test method success: "+ result.getName()+ " and time is: "+getCurrentTime());   
  }
   
  @Override //Called when the test-method execution fails
  public void onTestFailure(ITestResult result) {
    System.out.println("Test method failed: "+ result.getName()+ " and time is: "+getCurrentTime());   
  }

  @Override //Called when the test-method is skipped
  public void onTestSkipped(ITestResult result) {
    System.out.println("Test method skipped: "+ result.getName()+ " and time is: "+getCurrentTime());    
  }

  @Override //Called when the test-method fails within success percentage
  public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
    // Leaving blank   
  }

  @Override  //Called when the test in xml suite starts
  public void onStart(ITestContext context) {
    System.out.println("Test in a suite started: "+ context.getName()+ " and time is: "+getCurrentTime());   
  }
  
  @Override //Called when the test in xml suite finishes
  public void onFinish(ITestContext context) {
    System.out.println("Test in a suite finished: "+ context.getName()+ " and time is: "+getCurrentTime());   
  }
  
  //Returns the current time when the method is called
  public String getCurrentTime(){
    DateFormat dateFormat = 
        new SimpleDateFormat("HH:mm:ss:SSS");
    Date dt = new Date();
    return dateFormat.format(dt);    
  }
}





Java : @ Override

 Java : @ Override


The main reason @Override was created was to deal with simple (but nasty) typographical errors. For example, a method mistakenly declared as :  

public int hashcode(){
...



is in fact not an override - the method name has all lower case letters, so it doesn't exactly match the name of the hashCode() method. 

 It will however compile perfectly well. Such an error is easy to make, and difficult to catch, which is a dangerous combination. Using the @Override annotation prevents you from making such errors. 

http://www.javapractices.com/topic/TopicAction.do?Id=223

Thursday, January 30, 2014

Selenium : Screenshot in TestNG Report

Screenshot in TestNG Report





Code Here :


public class ff extends SeleneseTestBase {
public WebDriver driver;
StringBuffer verificationErrors=new StringBuffer();

@Test
public  void test2() throws InterruptedException {

     try{
    driver.findElement(By.xpath("//*[@id='containerrrr']/div[2]/h2"));
     }catch(Throwable  t)
     {
    verificationErrors.append(t.getMessage());
    Reporter.log("object not found"+"<br>");      
    //Take screen shot and give path in the report
    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("C:\\1.jpg"));
    Reporter.log("<a href=\"" +"file:///C:/1.jpg" + "\">Screenshot</a>"); // give path in the report
     }
//System.out.println(driver.findElement(By.id("gbqfba")).isDisplayed());
     
     clearVerificationErrors();
if (!"".equals(verificationErrors.toString()))
fail(verificationErrors.toString());
}
}

Selenium : Report Error in TestNG without Halting the Execution

 Report Error in TestNG without Halting the Execution

 

 

Note:

  1. Extend your class with "SeleneseTestBase"
  2. Declare a member varibale of type "StringBuffer".
Ex: 
Class abc extends SeleneseTestBase{

StringBuffer verificationErrors=new StringBuffer();

@Test
----------
----------
----------


}

 Code Here :

@Test
    public  void test1() throws InterruptedException {
     try{
         driver.findElement(By.xpath("//*[@id='containerrrr']/div[2]/h2"));
     }catch(Throwable  t)
     {
         verificationErrors.append(t.getMessage());
         Reporter.log("test1: object not found"+"<br>");
     }
     String fail_reason=verificationErrors.toString();
     clearVerificationErrors();
     if (!"".equals(fail_reason))
         fail(fail_reason);  
    }