Sunday 20 September 2015

Cobertura War Instrumentation and Coverage in a web application

In a day to day work we typically run our tests and presumably check that we are getting the expected results.Our tests may all pass with flying colours, but if we've only tested 50% of the code, how much confidence can we have in it? So a step ahead would be to ensure how much of the application code is exercised by our tests which ensures the quality of the tests that we typically run and thus code coverage comes into picture.

What is Code Coverage?
Code Coverage is a measurement of how many lines/blocks of the application code are executed while the automated/unit tests are running. Though code coverage is a white box testing methodology(as it requires knowledge of and access to the code itself rather than simply using the interface provided), we might come across situations where we need to analyse/collect code coverage metrics for our functional test cases.This post briefs the need of code coverage,coverage analysis,instrumentation for functional test cases with an example using Cobertura.

How is Code Coverage achieved?
Code coverage is collected by using a specialized tool to instrument the binaries to add tracing calls and run a full set of automated/unit tests against the instrumented product. A good tool will give you not only the percentage of the code that is executed, but also will allow you to drill into the data and see exactly which lines of code were executed during particular test. There are many coverage tools in market for Java Code Coverage -Cobertura,Clover,Emma,Jcoverage.In this post we will generate coverage metrics using cobertura -one of the most widely used java coverage tool as it has edge over other tools.

Features of Cobertura:
  • Open source Java tool.
  • Can be executed from simple ant build script.
  • Instruments Java bytecode after it has been compiled.
  • Can generate reports in HTML/XML by class name, percent of lines covered, percent of branches covered, etc.
  • Shows the percentage of lines and branches covered for each class, each package, and for the overall project.

What is instrumentation?
Instrumentation is all about manipulating the application code by injecting reporting code into strategic positions. In fact, the art of instrumentation falls in either of the two: class instrumentation and source instrumentation. Not surprisingly, the difference is that class instrumentation injects the reporting code directly into compiled .class files while source instrumentation creates an intermediary version of the sources which are then compiled into the final, source-instrumented .class files. Most of the code coverage tools will follow either of these instrumentation techniques.

For this post we are using a sample war file from (https://tomcat.apache.org/tomcat-6.0-doc/appdev/sample/)for instrumentation wherein for real time scenario,this should be replaced with your application war file.

Sample Cobertura War Instrumentation and Coverage in a web application

PreRequisite:
  • Tomcat 7 and above
  • JDK 1.7 and above
  • Ant 1.8 and above
  • Cobertura 1.9 and above
  • A sample war file for instrumentation/use your application war file

Pre-coverage steps:
  • Extract classes from your war.
  • Create an ant script for instrumenting the classes.
  • Add required libs/dependencies for instrumentation (Sample attached- Refer build.xml and build.properties).
Coverage steps:
  • Perform Cobertura instrumentation using your build target as below.
  • Now we have instrumented classes generated as below ,Replace the generated files in the war (replace with the existing classes) and cobertura.ser file generated.
  • Put your updated war in the tomcat webapps.
  • Put your cobertura.ser file in the tomcat bin .
  • Add cobertura.jar in the tomcat lib .
  • Start your tomcat.
  • Hit the required test cases (run ur web application flows either manually or through your automation scripts)
  • (for this sample war -we are hitting http://localhost:8080/sample home page -this application has Hello page-hello class alone so we are executing a test to hit the hello page)
  • Now put the updated cobertura.ser in the project ant home folder
Post-coverage steps:
  • Run coverage targets as below.
  • Now we have coverage for the test cases that we have run!

Monday 17 August 2015

Automated Visual Testing with Selenium and Applitools

      UI comparison across multiple resolutions with different dimensions such as Content, Layout, cross browsers is a difficult task with the help of manual testing. 

Why should visual testing be automated:

1. Lot of areas needs to be covered such as browsers, devices, screen resolutions, RWDs etc.
2. Manual visual testing is error prone and time taking.
3. In the process of “Continues Deployment”, it is mandatory that every task should be automated.

In the search of a automated tool for this purpose, many things comes in mind. Particularly, when we think about open source tools, selenium will be the first choice. But we cannot accomplish the task with selenium due to certain limitations such as desktop application support, iOS support, screenshots comparison etc.

Now in Paid tools, there is a tool named applitools which is designed for this particular purpose. The Applitools is the Applitools Eyes automatically validates the correctness of the UI layout, content and appearance on all browsers, devices and screen resolutions, and enables to automate tests that can only be done manually without it. 

Features of Applitools:
  • Automated testing of all the visual aspects of your application:
  • One simple test validates all the fields on a given screen.No need to write separate test for each UI element on the screen
  • Easy integration with existing test automation and ALM frameworks:
  • Test automation tools: Selenium, Appium, MS Coded UI, HP QTP (coming soon) and more.ALM tools: HP QC, MS TFS, IBM Rational Quality Manager, Atlassian, Rally and more.Cloud testing environments.
  • Seamless testing on multiple platforms, screen-resolutions and form-factors:
  • Define expected results or volatile areas for one browser, one screen resolution or one form factor and all tests would automatically be updated in all browsers, all screen resolutions and all form factors. Any change in your application should only be approved once in one specific test and all other tests would automatically be updated for all browsers, all screen resolutions and all form factors
  • Visual self-explanatory logs:
  • No more reading of complex text-based failure logs.
    Visual test timeline points you immediately to any failed steps.
    Smart visual test playback shows step by step the user actions and the screen displays during a test.
You can find more about applitools from https://applitools.com/

Now in this article we are going to learn about integrating applitools with selenium.


1. Download the latest version of the Eyes Java Selenium SDK from https://store.applitools.com/download/eyes_selenium_java/ and extract it to a folder of your choice. Add the extracted files to your path.

2. When running tests, make sure to use your personal API key: XFkqR77qRm9GZkvw9STuox8gBrECZt298F1101ur39cioY110

Sample code is as below:

public static void main(String[] args) throws URISyntaxException, InterruptedException {
        WebDriver driver = new FirefoxDriver();
        Eyes eyes = new Eyes();
        // This is your api key, make sure you use it in all your tests.
        eyes.setApiKey("XFkqR77qRm9GZkvw9STuox8gBrECZt298F1101ur39cioY110");
        try {
            // Start visual testing with browser viewport set to 1024x768.
            // Make sure to use the returned driver from this point on.
            driver = eyes.open(driver, "Applitools", "Test Web Page", new 
            RectangleSize(1024, 768));
            driver.get("http://applitools.com");
            // Visual validation point #1
            eyes.checkWindow("Main Page");
            driver.findElement(By.cssSelector(".features>a")).click();
            // Visual validation point #2
            eyes.checkWindow("Features page");
            // End visual testing. Validate visual correctness.
            eyes.close();
        } finally {
            // Abort test in case of an unexpected error.
            eyes.abortIfNotClosed();
            driver.quit();
        }
    }
 }
3. after running a test for the first time, it will automatically be saved as a baseline for future test runs. Now run your test again and open Applitools eyes to analyze the changes. For each step either 'Accept New' in    case the changes are expected or 'Keep Baseline' in case the changes reflect a bug.

Advantages of this integration:

  • Single page validation replaces hundreds of lines of validation code and hours of manual testing.
  • Automatic maintenance – approved changes are automatically propagated to other tests and execution environments.
  • Cognitive vision – avoiding false positives, by ignoring differences that are invisible to the human eye.
  • Automatically test your app in multiple languages.
  • Easily tests complex application pages including dynamic content, size and moving elements.
  • It takes the pressure off manual QA and increases the coverage, test faster & more accurately.
This is one of the effective tool to automate Visual Testing in Mobile, Web, Desktop Applications. Happy Testing :) 

Wednesday 12 August 2015

Do Makeup to your Jenkins Server

   In continuous Integration Process Jenkins plays a major role in terms of providing a very good platform to perform the task. It gives us the basic requirements such as normal UI, Trend chart. However it is always useful to have comprehensive dash boards, trend charts for better tracking purpose and eye catching UI themes that makes difference. We can also change the email configurations such as Subject lines, body content, including the report into the body of the email etc. For every requirement that is mentioned above, jenkins provides us the plugins. We will tweak those plugins and add the changes that we need. 

HTML Publisher
This plugin is handy with built-in copy to master functionality. Imagine that you have some files generated through your builds that are not actual artifacts. Let’s say logs, execution reports. This plugin lets you to copy them to a master and provide an easy HTML file that will have links to these special files of yours for really quick access.
    To configure this follow the below steps:
1. Click on the Configure option for your Jenkins job.
2. In the post build portion, look for the Publish HTML Reports option and select the check box. See the screen shot below


Fill the path to the directory containing the html reports in the "HTML directory to archive" field. Specify the pages to display (default index.html); you can specify multiple comma-separated pages and each will be a tab on the report page. Finally, give a name in the Report Title field, which will be used to provide a link to the report. By default, only the most recent HTML report will be saved, but if you'd like to be able to view HTML reports for each past build, select "Keep past HTML reports."

Some time at HTML directory, you don't have to specify project name, but have to start one level below. For e.g. if your project name is "ABC" and if HTML files are at "ABC/report-output/html" then you have to specify just \test-output\html\.

3. After saving the configuration, run build once. The published HTML reports are available to view from within Jenkins with convenient links in the dashboard.

Green Balls
Historically Jenkins has used the blue color to denote successful builds. So, all status messages throughout the GUI use blue as the color of success. But if you feel that green is the way to go (Green Hornet, Green Lantern, Gumby, traffic lights, etc) then you can change your preference to green with the Green Balls plugin.

Simple Theme Plugin:
This is a plugin for Jenkins that supports custom CSS & JavaScript.
You can customize Jenkins's appearance (ex. his gentle face on the background) as below:

Navigate to Jenkins > Manage Jenkins > Configure System > Theme
Set URL of theme CSS and JS to URLs of your customized CSS and JS

Some example themes are as below:
http://daniilyar.github.io/Jenkins-themes/themes/canon-jenkins/min/styles.css
http://daniilyar.github.io/Jenkins-themes/themes/canon-jenkins/min/script.js

Wall display Plugin:
A wall display that shows job build progress in a way suitable for public wall displays. Rendering is performed using javascript based on REST API calls, so requires no page refreshes.
After installing the plugin you will get a option on the left hand sidebar.To get it display simply click on the 'Wall Display' link in the sidebar of your project.

Email Extension Plugin:
This plugin allows you to configure every aspect of email notifications. You can customize when an email is sent, who should receive it, and what the email says. 


After installing this, go to the job, which has to configured for mail trigger, Click on “configure”. Go to the postbuild actions, click on “Editable Email Notification”. This will have options like the recipent details etc. Select “HTML(text/Content)” for “Content Type” option. under the Default content text area type the below text as it is though it contains html tags.

Hi All,

 Please find the overall Results of this build as below. You can click on http://10.40.60.186:8080/view/MCS/job/LETSCRETSAutomation/HTML_Report/ for more details.


${FILE,path=”test-output/emailable-report.html”}


Bottom of the line in the above script specifies the path. Change it according to your html path. Remember here, if ur html report depends on any resources like images etc, we have configure them accordingly.

https://wiki.jenkins-ci.org/display/JENKINS/Email-ext+plugin

Dash Board Plugin:
This plugin contributes a new view implementation that provides a dashboard / portal-like view for Jenkins.
The configuration is done in 2 parts, selecting the Jenkins jobs to include in the view, and selecting which dashboard portlets to have included in the view.  The jobs that you select are used for all the portlets to draw their information from. 

 

Monday 2 March 2015

XPath Writing Techniques and Strategies

Introduction:

        This article illustrates on how we can identify the objects in an Optimized manner using XPath which are reliable and consistent. We observed that there are applications which deal with different kind of objects; not having any id/name(s) and many dynamic objects not having any unique identification. Also there are lots of technologies integrated in an application such as GWT, DOJO, Flash etc which makes it difficult to develop a consistent code.
       
       So handling such complex scenarios and making scripts run successfully, is a big challenge. This article describes accurate methodologies with xpath and Xpath axes to overcome such difficulties.

Basics of XPath :
         In Selenium automation, the XPath is a very powerful way to parse the HTML code of any web page and find out the XPath path for identifying the elements on the web page. If properly used, it can produce very reliable and low maintenance locators. But when used an inefficient xpath, it can lead to very inconsistent results.
         XPath is a syntax for defining parts of an XML document. It uses the path expressions to navigate in XML documents. It is like a small programming language, it has functions, expressions, wild card characters etc. XML documents consist of trees of nodes. The topmost element of the tree is called the root element followed by descendant nodes.
Let’s look into the terminology used to identify these nodes: 
  • Each element has one parent except root
  • Each element may have zero or one or more child elements referred as child Nodes can have same parent called siblings. Among siblings, the nodes which are to the immediate left are referred as preceding-sibling and other left nodes as preceding. The nodes to the immediate right are referred as following-sibling and other right nodes are referred as following.
  • A nodes parent, parent’s parent is referred as Ancestor
  • A nodes children, children’s children is referred as Descendant
XPath Axes:
An axis defines a node-set relative to the current node.
Image
Following example explains the various facets of Xpath identification
 Image
In the above example we illustrate by considering Employee2 as node for reference for referring to other nodes
Employee2 node has
  • Employee3 as following sibling
  • Employee1 as Preceding sibling.
For Employee2,
  • Manager1 is the parent
  • Department is the ancestor (Parent of Parent).
For Employee2,
  • Section is the Child node
  • Employee4 and Employee5 are Descendant nodes
Optimization of XPath
         We observed that there many cases where simple changes are made to the application and previously identified XPath Statements won’t work. In order to avoid such problems, it’s necessary to optimize the XPath Statements before using them in Selenium Automation.

         The Advantage of Optimizing the Xpath Statements are to get the shortest and least breakable XPath Statements.
Following are the few strategies in order to optimize the XPath:
  1. Use id attribute if available
  2. Use the combination of attributes to make the XPath more specific
  3. Use the Relative XPath instead of Absolute XPath Statements
  4. Always avoid using indexes in Xpath.
  5. Verify the xpath using Selenium IDE commands
  6. Using … to move to parent of the present node
  7. Use XPath functions in XPath wherever necessary to better identification
  8. Identification of objects with same attribute values
  9. Don't identify the images using src or alt attributes
  10. Handling dynamic attribute Values
  11. Handling multiple Xpaths for a single object
Let’s look into each of them in detail:
Consider the following XML example “Example1” for illustration of these strategies
Example-1
</pre>
<table>
<tbody>
<tr id="item1">
<td class="name item">Mp3 Download: foobar.mp3</td>
<td class="name item">
<input class="name item form field disabled" type="text" name="qty" />
</td>
</tr>
<tr id="item2">
<td class="name item">Mp3 Player</td>
<td class="name item">
<input id="item2_quantity" class="name item form field required" type="text" name="qty"/>
</td>
</tr>
</tbody>
</table>
<pre>

Use ID attribute if available
If the ID attribute is present for an object, use it in XPath even though the object can be identified with any other attributes. ID attribute should have the highest priority. For example : Based on Example1, It can be used as
//tr*@id=’item1’+
@ symbol indicate following is an attribute of the object.

Use combination of attributes in XPath
If ID attribute is not available, any other attribute which uniquely identifies the object can be used. Also combination of 2 or more attributes can be used to identify the object such as name, type, class, value etc. This will make the XPath more specific. For example, based on Example1, we can have
//input*@type=’text’ and @name=’qty’+
In the above example Boolean operator ‘and ‘operator is used in XPath statement to combine more than one attributes.
Using combination of properties in XPath is useful in following cases
There are cases where there does not exist any single attribute which uniquely identify the object
 Even if there is exist single attribute which uniquely identifies the object, we can use combination of attributes to make Xpath more robust and hence there is less chances of failure in identification.

Use Relative XPath instead of Absolute Xpath
Absolute Path refers that Xpath starts from root i.e. from ‘/’ to till the desired html element is reached such as /html/body/p[2].
Relative path refers to the Xpath that starts from specific point to the desired element. It starts with ‘//’.
It is always recommended to use Relative Xpath then Absolute xpath for following reasons.
  • Absolute Xpath will be very long compare to Relative xpath and hence difficult to manage
  • In case of Absolute Xpath , there are high chances that Xpath may break even if there are small changes introduced
  • Absolute Xpath has the disadvantage of typing the expression to a particular input structure
For example, based on Example1, we can have an absolute path as follows
/pr/table/tbody/tr*@id=’item1’+
Using Relative path we can have
//tr*@id=’item1’+

Avoid Using Indexes in XPath
In XPath always avoid using indexes to identify a specific node. These are not reliable and with slightest modification xpath may break.
Let us see example Exmaple1:
You can target the highlighted input field using
xpath=//table/tr[2]/td/input
xpath=(//table[@name='cart']//input)[2]
xpath=//input[@id='item2_quantity']
xpath=//input[contains(@class='required')]
 xpath=//input[contains(@class='required')] and @type='text']
As you can guess, the first two expressions are not as reliable as others. Of these //table/tr[2]/td/input is the worst because it would break even with slight modifications to the page structure. In any case do not rely on tools, including selenium IDE, to generate the right xpath expression for you – they are usually the worst.
It always advisable to code the Selenium test to find that item in relation to an existing item that *has* been programmed properly rather than to rely on meaningless indexes. This means, when reading through your script you are more likely to understand where
//input[@id='BottomTotal']/following-sibling::input[contains(@value,'Add')]
is compared to
//li[6]/input[4].
This becomes more obvious when you have a large number of tests in your test suite.

Verify the xpath using Selenium IDE commands
Once Xpath is formed, verify it using Selenium IDE. There are cases where a specific Xpath may satisfy two or more objects. Use “highlight” command in Selenium IDE to highlight the intended object. This will ensure that Xpath is accurate.
Further we can also use “click”, “verifyVisible” , “type” etc. command in selenium IDE to verify the object.
It is advisable to use both “highlight” as well as “verifyVisible” commands to verify the as some of the objects may successfully highlight but not visible.
“click” command can be used for objects such as “Button” and “type” can be used to type the characters into a text box.

Using .. (double dot symbol) to move to parent of the present node:
Assume that you are in a specific node and want to move to parent of that node then it is advisable to use .. (double dot symbol) to navigate to parent node then using Parent::<node
type> or ancestor::<node type>. This will reduce the length of the XPath and identification of node faster during execution.
In XPath . (a Single dot) refers to present node and ..(a double dot) refers to parent of present node. Consider the following example
Based on Example1, the parent of the node td i.e. tr can be reached using
//td*@class=’name item’+/../*@id=’item1+

Use XPath functions in XPath wherever necessary to better identification
As XPath is a Programming Language, it has many built-in functions which we can use in Xpath Statements. During selenium automation, sometime there are problems of identifying the objects on a page which have same attributes there is no way of distinguishing them. In such cases XPath function comes very handy
Some of the XPath functions used are:
Position() –This function is for locating specific html tag such as //input[position()=5] to locate 5th element
Last() – This function is for locating last element node of the specific node type such as //input[last()].
Further it can be specified as //input[last()-1] to identify an node before the last node
Starts-with()- This is one of the predefined methods of XPath Language which is used in XPath Statements to locate the element starting with the specified text or to locate the element node containing an attribute value which is starting with the specified text.
For Example
//div[starts-with(text(),’Approver’)+ -Matches the element with string which begins with ‘Approver’
//div[starts-with(@id,’test’)+ – Matches the element with attribute begins with string ‘test’
Contains () –This is one of the predefined methods of XPath Language which is used in XPath Statement to locate the element node containing specified text on the page or to locate the element node containing specific text in its attribute value.
For example
//span*contains(text(),’Approver’)+—Matches any element with text contains the string ‘Approver’
//span*contains(@id,’testing’)] – Matches any element with id attribute containing string ‘testing’

Identification of objects with same attribute values
There are cases were two objects have same attribute value in a specific web page. In such cases identify a nearby object with unique identification and then navigate to intended object.
Consider the following example:
In the below example there are 2 checkboxes with same name as resendChkBox, so to identify such cases we can initiate relative X-Path with Escalation Rule value and proceed to that checkbox object.
//td[text()='Escalation Rule #1']/parent::tr/following-sibling::tr/descendant::span/input[@name='resendChkBox']
//td[text()='Escalation Rule #2']/parent::tr/following-sibling::tr/descendant::span/input[@name='resendChkBox']

Don't identify the images using src or alt attributes
The objects of type Image can be usually identified by src and alt attributes such as
//img[contains(@src,'cancel')]
//img[@alt='Search']
But it is not suggestable to use src or alt as these two attributes does change quite frequently.

Handling dynamic attribute Values
If we need to use value of an attribute which is dynamic, then we can use Selenium.getAttribute or selenium.getText or any other methods to fetch the values and use it in a XPath
As for example:
String fetchText=selenium.getAttribute("//a[contains(text(),'click')]/@href")
In this case the value of href attribute will be stored in a variable fetchText .
Similarly in the following case the the text value of element with name containing ‘testing’ will be stored in the variable p.
String p=selenium.getText("//p*contains(@name,’testing’)+")

Handling multiple Xpaths for a single object
        Consider the below scenario, where the home page of the application is having multiple versions(Ex: Version A, Version B, Version C etc) and it displays random version of the page depending upon server hit. Now the test scenario is to check the Logo of the company. This logo is under <div> in Version A, <img> in version B, <span> in Version C. As we are not sure of the page when we hit the URL, it is difficult to identify the logo object.
       To handle such scenario, we have '|' (pipe) symbol. Using this, we can combine more than one xpath for a single object. For the above explained scenario Xpath looks like as below:
//div[contains(something)]|//image[something]|//span[something]

Some Illustration on usage of XPath
//a[text()='ApproverName']/ancestor::td/preceding-sibling::td/input
//span[text()='Confirmation Instructions:']/ancestor::td/following-sibling::td/descendant::a/img
//div[text()='Send Reminder Every']/parent::td/following-sibling::td/descendant::td/select
//td[text()='Escalation Rule #1']/../following-sibling::tr/descendant::td/div[contains(text(),' Use for the first')]/input

             Though this articles gives the clear information about the usage of keywords and their examples, the scenarios which makes us strong in using these keywords.

Monday 16 February 2015

Generating HTML Alerts Report through ZAP API

In our previous post we have seen how to use ZAP API for automated security testing. This post deals with generating the alert report.

When the user automates the security testing, he/she looks for below kind of reporting.

  • alerts based on id 
  • alerts for the baseurl
  • html consolidated report 
    
        With the help of getAlerts() method of zaproxy class, we can generate the alerts based on id and url. For generating the consolidated report, API doesn't support HTML report generation as it does by ZAP tool. But it generates xml report. As a work around we can generate this xml report and convert that into HTML with the help of XSLT file.

Users can get the XSLT file from the below path:
https://code.google.com/p/zaproxy/source/browse/trunk/src/xml/report.html.xsl

The below code snippet will be handy in converting xml report into HTML report
        public void generateHTMLReport() throws ClientApiException, TransformerException, IOException{
TransformerFactory tFactory=TransformerFactory.newInstance();
InputStream is = ZAProxyScanner.class.getResourceAsStream("<XSLT REPORT PATH>");
Source xslDoc=new StreamSource(is);
Source xmlDoc=new StreamSource(new ByteArrayInputStream(clientApi.core.xmlreport("")));
OutputStream htmlFile=new FileOutputStream("<PATH TO GENERATE HTML>");
Transformer trasform=tFactory.newTransformer(xslDoc);
trasform.transform(xmlDoc, new StreamResult(htmlFile));
htmlFile.close();
         }


Happy Testing :)

Automated Security Testing with ZAP API

      The OWASP Zed Attack Proxy (ZAP) is an easy to use integrated penetration testing tool for finding vulnerabilities in web applications.

      It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing as well as being a useful addition to an experienced pen testers toolbox.

Zed Attack Proxy Features:
The latest version of ZAP 2.x is a client that runs on Windows, Linux and MacOS and requires Java 7. Here is a list of the main features:
  • Intercepting Proxy
  • Automated Scanner
  • Passive Scanner
  • Brute Force Scanner
  • Fuzzer
  • Port Scanner
  • Spider
  • Web Sockets
  • REST API
To know more about ZAProxy Tool, please visit: https://code.google.com/p/zaproxy/

Legal disclaimer: Only run ZAP against your own environments, i.e. Test, Staging environments. It is illegal to attack websites from competitors or other people.

In this post we will discuss about Automating Security Testing with the help of Selenium and ZAP API.


      ZAP provides a REST Application Programming Interface (API) which allows you to interact with ZAP programmatically.The REST API can be accessed directly or via one of the client implementations detailed below.In order to be able to use the API when using the ZAP UI you have to first enable it.

You can do this via the Options API screen:
Tools / Options... / API

     If you run ZAP in 'headless' or 'daemon' mode (by starting ZAP via the command line and using the -daemon flag) then the API will be automatically enabled.

Download ZAProxy tool and install it. 

Download Sample automated project from the below path:
https://github.com/continuumsecurity/zap-java-api/
Install POM.xml in local system and keep the project ready to run.

Now to start ZAP in headless mode, go to C:\Program Files\OWASP\Zed Attack Proxy where your ZAP got installed. From the directory open zap.bat and paste the below code and save it.

java -Xmx512m -XX:PermSize=256M -jar zap.jar -daemon

Now in the code use the below command to invoke the ZAP with headless mode:
Process p =  Runtime.getRuntime().exec("cmd /c zap.bat", null, new File("C:/Program Files/OWASP/Zed Attack Proxy/"));

From the dowaloaded github code, 'ZAProxyScanner.java' is the most important class which holds all the methods related to ZAP.

       Use spider method before scanning of the Application. This spidering can uncover the URL which we are not visting as part of the test execution.

This project structure can be used to write our own test cases with TestNG integration framework.

For the information related to Test results please check the other post. :)

Image reading with Tesseract OCR API

       Tesseract is an open-source OCR engine that was developed at HP between 1984 and 1994.It is an optical character recognition engine for various operating systems(Includes windows, linux and Mac).It is free software, released under the Apache License, Version 2.0, and development has been sponsored by Google since 2006.Tesseract is considered one of the most accurate open source OCR engines currently available.

        This can be used effectively with Selenium for reading text from images, where sikuli may not be effective. Along with English, it also supports native languages such as Turkish, Spanish, Hindi, Swedish etc. This has typical architecture where we can feed the train data for the image recognitions.

The Process of integrating Tesseract OCR with java project is as below
Step1:
We need a JNA wrapper to use tesseract in our java project. We can use tess4j for this. It can be downloaded from here http://tess4j.sourceforge.net/

Step2:
Now extract the contents of the tess4j archive to workspace location.

Step3:
From eclipse, Open the Tess4j project.

Step4:
Now open a new project in eclipse and type below code:

import java.io.*;
import net.sourceforge.tess4j.*;
public class MySample {
public static void main(String[] args) {
File imageFile = new File(“<path of your image>”);
Tesseract instance = Tesseract.getInstance(); 
try {
String result = instance.doOCR(imageFile);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
}
}

Step5:
Now expand the Tess4j project and expand source packages; inside you will find 3 packages. Copy all of them into your project’s source packages. It should now look like as shown below.


















Here "OCR" is the project I created.

Step 6:
Right click on the project. Go to Build Path--> Configure Build Path--> Add external JARs.


















Navigate to the location where you extracted the tess4j archive. Open the folder (Tess4j) and navigate to lib. There you will see 4 jar files. Choose all of them and click open. Your project space should look like as shown below now. 


Step 7:
Now you will find 2 dll files in the Tess4j folder (The folder which you extracted) namely liblept168.dll and libtesseract302.dll. Copy these two files into the src package and it should now look like as shown below.
















Thats it…!!! You are done. When you run this code, it should display the text content in console window of Eclipse.