Saturday 8 November 2014

Invoke Maven Project by - Jenkins !!



How to invoke maven project through Jenkins steps are below :-

1. Download and install jenkins.

2. Run jenkins.war by following command :-

java -jar jenkins.war --httpPort=9090
If you want to use https use the following command:
java -jar jenkins.war --httpsPort=9090

3. Create Jenkins Job:-

Create TestMaven Job


before creating job ensure that you set jdk path in jenkins configuration.


4. Set your POM.xml file path and build jenkins job :-









Done :)

For Creating Maven Project :- Link





Friday 7 November 2014

How To Create Maven Project !!


Here is the way to create way to create maven project :-

1.) Install Maven in your latest eclipse.

2.) Create Maven Project.

3.) Create Below Java file in package com under src/main/java -

package com;
import javax.swing.JOptionPane;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class TestClass {
   
     public static void main(String[] args) throws InterruptedException {
            // Create a new instance of the firefox driver
            // Notice that the remainder of the code relies on the interface,
            // not the implementation.
            WebDriver driver = new FirefoxDriver();

            // And now use this to visit Google
            driver.get("http://www.google.com");

            // Find the text input element by its name
            WebElement element = driver.findElement(By.name("q"));

            // Enter something to search for
            element.sendKeys("cheese!");

            // Now submit the form. WebDriver will find the form for us from the element
            element.submit();

            Thread.sleep(5000);
            // Check the title of the page
            JOptionPane.showMessageDialog(null, "Page title is: " + driver.getTitle());
                
            driver.quit();
        }

}

4.)  Edit your pom.xml

Here is edited  pom.xml :-

<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>kepler_maven</groupId>
    <artifactId>kepler_maven</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.44.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.1.1</version>
                <executions>
                    <execution>
                        <phase>test</phase>
                        <goals>
                            <goal>java</goal>
                        </goals>
                        <configuration>
                            <mainClass>com.TestClass</mainClass>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

5.) Run pom.xml as Maven Install

6.) Here is the complete zipped project Maven Sample Project

Done !!





Thursday 16 October 2014

Automatic File Download Selenium Java



Below code snippet for Firefox :-

Automatic File Download Selenium Java

---------------------------------------------------START-----------------------------------------------------

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import atu.utils.windows.handler.exceptions.WindowsHandlerException;


public class autoDownLoad {

public static void main(String[] args) throws WindowsHandlerException, InterruptedException {

 FirefoxProfile profile = new FirefoxProfile();
 String path="d:\\downloads123";
 profile.setPreference("browser.download.folderList", 2);
 profile.setPreference("browser.download.dir", path);
 profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
 profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword,application/csv,text/csv,image/png ,image/jpeg, application/pdf, text/html,text/plain,application/octet-stream");
 profile.setPreference("browser.download.manager.showWhenStarting", false);
 profile.setPreference("browser.download.manager.focusWhenStarting", false); 
 profile.setPreference("browser.download.useDownloadDir", true);
 profile.setPreference("browser.helperApps.alwaysAsk.force", false);
 profile.setPreference("browser.download.manager.alertOnEXEOpen", false);
 profile.setPreference("browser.download.manager.closeWhenDone", false);
 profile.setPreference("browser.download.manager.showAlertOnComplete", false);
 profile.setPreference("browser.download.manager.useWindow", false);
 profile.setPreference("browser.download.manager.showWhenStarting",false);
 profile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
 profile.setPreference("pdfjs.disabled", true);
 WebDriver driver = new FirefoxDriver(profile);
driver.get(YOUR URL);
}

}


More Type--- > MIME TYPES

-----------------------------------------------------END------------------------------------------------------

Monday 22 September 2014

Loggers In Ruby



require 'logger'

logger = Logger.new($stdout)
logger.warn("This is a warning")
logger.info("This is an info")


//$stdout redirects all logs to console. If you want to redirect all this to a file then //need to initialize $stdout='/home/Aman_Test/log.txt', 'w'

Monday 1 September 2014

Selenium WebDriver and AutoIT

It is often possible in this web world that we get to work with objects which is either out of box,flash or webpages that are added with extra layer of security like a single sign-on for example windows credentials


Also another example is if one works with Microsoft technologies or Oracle CRM Web Applications which are only compatible with IE browsers there LOV(List of Values) popup , not to forget the modal popup

In the above situations it's hard to achieve or progress with automation with Selenium RC/Selenium WebDriver 

Hence the simplest and fairly easy option is AutoIT

What is AutoIt ?

AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying "runtimes" required!

Let's get started with having AutoIt installed on your local box

Download latest version of AutoIt from the official release page here 

It's better you download AutoIt Full Installation which will help you in scripting & compiling as well

Once installation is completed you should see the application being installed in your All Programs or which ever location you have installed

Now, let's get started - What is that we are trying to automate or use AutoIt for

Given this Scenario : Of Logging in the windows Authentication to your webapplication

Just like the below screen shot



Windows login modal as popped out by Windows OS :

Here is how the AutoIt Script should look


WinWaitActive("Connect to yourservername","","60")
  If WinExists("Connect to yourservername") Then 
     ControlSend("Connect to yourservername","", "[CLASS:Edit; INSTANCE:2]","DomainName\username")
     ControlSend("Connect to yourservername","", "[CLASS:Edit; INSTANCE:3]","Password") 
     ControlClick("Connect to yourservername","","[CLASS:Button; INSTANCE:3,button[,clicks[,153[,223]]]]") 
EndIf 



Once you have the above script compiled - You are all ready to use them in your webDriver / selenium RC script
 so here is example for JAVA

So here's the code that goes in your webDriver script

        @BeforeClass 
        public static void setUp()
        {
              System.setProperty("webdriver.ie.driver", "C:\\Eclipse\\Selenium\\IEDriverServer.exe");
              driver = new InternetExplorerDriver();
              driver.get("your url");
              try {
                        Runtime.getRuntime().exec("C:\\Eclipse\\Selenium\\Autentication.exe");
                  } catch (IOException e) 
                  {
                              e.printStackTrace();
                   }
        }

You are all set now : both the code snippets together should help in working on Windows Authentication
 Courtsey : automationwithseleniumblog

Sunday 31 August 2014

How to use Logger in our JAVA simple projects / Programs


Simple way to use logger in our project

Steps to use :

1.) Download log4j jars link is lo4j.jars
2.) Try sample project in Eclipse or run normally link to download is Sample Logger Project


Sample program looks like :-

package TestLogger;
import java.io.IOException;
import Logger.LoggerInstance;

public class SampleClass {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
LoggerInstance loggerObj = new LoggerInstance();
System.out.println("Hello World");
LoggerInstance.logger.info("Hello World");
}
}

To use these Logger Instance we need to define separate class that you can find in dummy project or refer below class :-

package Logger;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

public class LoggerInstance {

public static Logger logger;
File directory = new File ("");
String absolutepath = directory.getAbsolutePath();
//This is to get location for creating log file. This value is comming from build.xml
String str_logFilePath = absolutepath+File.separator+"log";


public LoggerInstance() throws IOException
{
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = new Date();
System.out.println(date);
String current_dateTime = dateFormat.format(date);
System.out.println(current_dateTime);
current_dateTime = current_dateTime.replace("-", "_");
current_dateTime = current_dateTime.replace(" ", "_") ;
current_dateTime = current_dateTime.replace(":", "_") ;

File f1 = new File(str_logFilePath) ;
if(!f1.exists()){
f1.mkdir();
}
//System.out.println("00 " + str_logFilePath);

String str_logFilePath1 = str_logFilePath+File.separator+"LogFile_created_by_ASJ_"+current_dateTime+".log";
//System.out.println("11 " + str_logFilePath1);

File f2 =  new File(str_logFilePath1);
f2.createNewFile();


if(logger==null)
{
try{
logger = Logger.getLogger("ASJ");
FileAppender apndr = new FileAppender(new PatternLayout("%p %t %c - %m%n"),str_logFilePath1,true);
//apndr.setAppend(true);
logger.addAppender(apndr);
}
catch(Exception e)
{
System.out.println("Log file is not initialized");
}
}
}

}


So it is easy to run :-)

Tuesday 29 April 2014

Thursday 24 April 2014

Email Verification through Java

 We can verify Emails sample example is given for gmail :--
just add this jar file to your program :- Mail.jar

package Mail_ver;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.SubjectTerm;

public class mail_content_verification {
public static void main(String args[]) throws Exception {
 Properties props = System.getProperties();
       props.setProperty("mail.store.protocol", "imaps");

           Session session = Session.getDefaultInstance(props, null);
           Store store = session.getStore("imaps");
           store.connect("imap.gmail.com", "UserName",
                   "Password");

           Folder folder = store.getFolder("INBOX");
           folder.open(Folder.READ_WRITE);

           System.out.println("Total Message:" + folder.getMessageCount());
           System.out.println("Unread Message:"
                   + folder.getUnreadMessageCount());
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
   }
}

Tuesday 4 February 2014

Use of Robot Class (This sample code will show the use of Robot class to handle the keyboard events. If you run this code and open a notepad then this code will write hi budy in the notepad)

Java.awt.Robot class is used to take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code. This class is used generally for test automation. 

As we can handle windows based Modal dialog and file dialogs.

Sample Code :-

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class RobotExp {

public static void main(String[] args) {

try {

Robot robot = new Robot();
// Creates the delay of 8 sec so that you can open notepad before or we can call notepad from java


// Robot start writing
robot.delay(5000);
robot.keyPress(KeyEvent.VK_H);
robot.keyPress(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_B);
robot.keyPress(KeyEvent.VK_U);
robot.keyPress(KeyEvent.VK_D);
robot.keyPress(KeyEvent.VK_Y);

} catch (AWTException e) {
e.printStackTrace();
}
}


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

Send Ctrl + Z

robot.keyPress(KeyEvent.VK_CONTROL)
robot.keyPress(KeyEvent.VK_Z)
// CTRL+Z is now pressed (receiving application should see a "key down" event.)
robot.keyRelease(KeyEvent.VK_Z)
robot.keyRelease(KeyEvent.VK_CONTROL)
// CTRL+Z is now released (receiving application should now see a "key up" 
event - as well as a "key pressed" event).
------------------------------------------------------------------------------------
Use of TAB
    robot.keyPress(KeyEvent.VK_TAB);
    robot.delay(100);
    robot.keyRelease(KeyEvent.VK_TAB);

BY Using all above methods and robot class we can authenticate Windows login modal.

Monday 6 January 2014

Image Comparision in Java(Can use with Selenium)

Sample Prog:-

package ASJ_IMG_CMP;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;
import java.io.File;

class Image_CMP{
public static String imageComparison() {
System.out.println("Executing imageComparison");

try {

String file1 = "C:\\Documents and Settings\\amanjain\\Desktop\\1.PNG";
String file2 = "C:\\Documents and Settings\\amanjain\\Desktop\\2.PNG";

Image img1 = Toolkit.getDefaultToolkit().getImage(file1);
Image img2 = Toolkit.getDefaultToolkit().getImage(file2);

try {

PixelGrabber grab1 = new PixelGrabber(img1, 0, 0, -1, -1,false);
PixelGrabber grab2 = new PixelGrabber(img2, 0, 0, -1, -1,false);

int[] data1 = null;

if (grab1.grabPixels()) {
int width = grab1.getWidth();
int height = grab1.getHeight();
data1 = new int[width * height];
data1 = (int[]) grab1.getPixels();
}

int[] data2 = null;

if (grab2.grabPixels()) {
int width = grab2.getWidth();
int height = grab2.getHeight();
data2 = new int[width * height];
data2 = (int[]) grab2.getPixels();
}

System.out.println("Pixels equal: "
+ java.util.Arrays.equals(data1, data2));

if(java.util.Arrays.equals(data1, data2)==true){
    System.out.println("Both Images are Same");
}
else
    System.out.println("Both images are diffrent");

} catch (InterruptedException e1) {
e1.printStackTrace();
}
return "Pass";
} catch (Throwable t) {
// report error
return "Fail - " + t.getMessage();
}

}
public static void main(String args[]){
    imageComparison();
}
}