Monday, May 28, 2012

Defining project relationships in maven


Maven provides three ways to define project relationships

Dependency – Dependency relationships are useful when one wishes to use some API in the project/framework. Since the advent of maven 2.x dependency relation ship has got much stronger & usable, where one just needs to declare the project dependency and maven itself take care of transitive dependency.  
To define dependency, one needs to mention the repository, if jar does not exist in maven’s default repository and add dependency in pom.xml. One can define the repository in settings.xml as well but that would reduce the projects portability.

The example of declaration to include javaee in your project is as mentioned below –
 <repositories>
  <repository>
   <id>Java.Net</id>
   <url>http://download.java.net/maven/2/</url>
  </repository>
 </repositories>

 <dependencies>
  <dependency>
   <groupId>javax</groupId>
   <artifactId>javaee-api</artifactId>
   <version>6.0</version>
  </dependency>
 </dependencies>

Inheritance – Inheritance as the name suggests let the child projects inherit the parent’s elements. One can use inheritance in multi module project by making a parent project, extracting the common elements of module’s POM and putting them in parent project’s POM. After declaring the parent relationship in child’s POM the elements automatically become available in child project.

Maven provide the inheritance of following elements –
  • dependencies
  • developers and contributors
  • plugin lists
  • reports lists
  • plugin executions with matching ids
  • plugin configuration
Example of parent declaration in maven 3.0 project is as mentioned below -

    <parent>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-parent</artifactId>
  <version>21</version>
  <relativePath>../pom/maven/pom.xml</relativePath>
  </parent>
Note – In maven all the POMs by default inherit the super POM, which defines the default maven project structure,  default life-cycle and plugin for default life cycle activities

Aggregation – Aggregation is used in muti-module project; where one wants to centralize the build process of all the modules. He/She needs to create a aggregator project and declare all the module’s in it’s POM. During the build phase of aggregator project all the modules are built. The ordering of module does not matter. Maven always builds the dependency first and then project.

Example of aggregation in maven project is as mentioned below –
  <modules>
  <module>maven-plugin-api</module>
  <module>maven-model</module>
  <module>maven-model-builder</module>
  <module>maven-core</module>
  <module>maven-settings</module>
  <module>maven-settings-builder</module>
  <module>maven-artifact</module>
  <module>maven-aether-provider</module>
  <module>maven-repository-metadata</module>
  <module>maven-embedder</module>
  <module>maven-compat</module>
  <module>apache-maven</module>
  </modules>
References -
Super Pom -
http://maven.apache.org/guides/introduction/introduction-to-the-pom.html
POM Reference - http://maven.apache.org/pom.html
Maven 3.0 project pom - http://svn.apache.org/viewvc/maven/maven-3/trunk/pom.xml?view=markup

Saturday, May 19, 2012

Response compression in Apache (using mod_deflate)


In any web application's popularity it's performance plays a prominent role. To make sure that application has optimal performance, developer need to review the application, environment and target customer’s environment. Some solutions, which give performance boost for high bandwidth client, might fall flat for low bandwidth clients. If we are tuning our application for low bandwidth clients we need to minimize the network overhead in our application.

Among multiple ways to minimize the network overhead, response compression is one of the solutions. As response compression is not part of application’s business logic, we should not mix it with our application code.

With the advent of multi-feature servers, response compression can be configured in the servers now. Even browser supports the compressed response. The complete life cycle is managed in below steps –
  1. Client (i.e. browser) sends the request to the Server
  2. Sever passes the request to the application
  3. Application generates the response and provide it to server to be sent to the client (i.e. browser)
  4. Server checks whether the compression option of the specific mime type, being sent as response, has been configured.
  5. If yes, server compresses the data, add compression info into header and sends the compressed response to client.
  6. Client (i.e. browser) checks the header and knows that response it compressed, it decompresses it and renders/processes
 Apache web server provides an extension called mod_deflate to be used to achieve response compression of  specific type of mime object. To use it, we need to add below mentioned configuration in httpd.conf configuration file.

LoadModule deflate_module modules/mod_deflate.so

<Location />
   AddOutputFilterByType DEFLATE text/html text/plain text/xml application/javascript text/css
</Location>

Effectiveness – We achieve almost 75% compression, using mod_deflate. Below screenshots depict sample of compression level achieved using mod_deflate.

Response size before compression

Response size after compression - 

Places to avoid mod_deflate –
  1. Once should not use mod_deflate to compress images or videos.
  2. In high bandwidth environment, mod_deflate’s effect on performance should be checked before sending it to production. Because overhead of compression and de-compression activity (few milliseconds) might surpass the benefit of data transfer reduction. 
References -
Apache mod deflate - http://httpd.apache.org/docs/2.2/mod/mod_deflate.html

Thursday, May 17, 2012

Implementing Factory Design pattern using Type Safe Enum


When we have multiple similar type of objects and want to make such object creation process completely cohesive, we use factory design pattern.

There are two ways to implement it –
1.      Implementing the singleton factory class and then creating a method to generate the objects.
2.      Using type safe enum (in java) to create factory.

Here we will focus on second way of implementing factory design pattern.  There are following reasons to choose enum for factory implementation –
1.      Enum are inherently singleton.
2.      Enum can implement interface, which becomes the parent of each enum element.
3.      Enum provides easy way of avoiding code duplication by letting us develop common feature with same implementation in enum body and feature with different implementation in enum element body.
4.      Enum provides singleton implementation of each enum element.

Steps to implementing factory using enum–
Factory generates the similar type of objects. In other words all the objects generated by factory belongs to same super class/interface.

We can follow the below mentioned steps to generate factory -
1.      Develop an interface and declare the common features of the sub classes to it.
2.      Develop an enum, implementing the interface.
3.      Declare the enum properties adding specific implementation inside the body of enum element and common implementations inside enum.

Sample implementation –
Interface –
public interface Operation {
    double evaluate(double a, double b);

    String operationName();
}
Enum as factory –
public enum NumberOperation implements Operation {
    ADDIION("Addition") {
        public double evaluate(double a, double b) {
            return a + b;
        }
    },
    SUBSTRACTION("Substraction") {
        public double evaluate(double a, double b) {
            return a - b;
        }
    },
    MULTIPLICATION("Multiplication") {
        public double evaluate(double a, double b) {
            return a * b;
        }
    },
    DIVISION("Division") {
        public double evaluate(double a, double b) {
            if (b == 0)
                throw new IllegalArgumentException(String.format(
                        "%s is not supported as denominator for division", b));
            return a / b;
        }
    };

    private String operationName;

    private NumberOperation(String operationName) {
        this.operationName = operationName;
    }

    public String operationName() {
        return operationName;
    }
}
Limitations -
Enum can implement interface but can not extend abstract class. The workaround for it is to implement interface and develop common code in enum body. As we did in above mentioned example

Sample project –
The sample project with the above factory implementation can be downloaded from here.

In this project, we have developed a small requirement where client requirement was to provide implementation of addition, subtraction, multiplication and division.

During this design of sample program, we used TDD considering tests as our client and used below design patterns and design principals –
  1. Factory Design pattern
  2. Facade Design pattern
  3. Bridge Design pattern
  4. Strategy design pattern
  5. Singleton design patter (inherent in enum)
  6. Dependency inversion
  7. Cohesion
  8. TDD
To execute the project you will need maven 3 & java 5.0 or above installed in your application.  To check the program in execution use the following steps –
1-     Download and extract the zip
2-     Run mvn clean eclipse:eclipse test-compile
3-     Import the project into eclipse and execute NumberOperationSpec as JUnit.

Friday, May 11, 2012

Including page number and page count in JasperReports Footer


Multiple times, we come across such a requirement, where we need to display page number and page count info in report's footer.These footers help the viewer in identifying the proper sequence of pages after the report is printed.

The challenge in such scenario is to identify the total page count even in the first sheet of the report.

JasperReports provide us fine grained control on the time, when a specific text filed expression should be evaluated.Possible evaluation timings are Now, Report,Group, Band,Page,Column,Auto. We can use JasperReport's build in system variable "PAGE_NUMBER" to get the page number during the evaluation time.

To add page number/total page count info in report footer, we divide the complete info into two below sections on the basis of evaluation time.
  1. The info,which should be evaluated and printed as soon as the control reaches (Page Number and "/")
  2. The info which should be evaluated and printed when the complete report is created (Total Page Count)
Then we add two text  field in the report footer mentioning the evaluation time of second text field as Reort. Fist section will print the page number at default evaluation time (ie now).

Sample code- 
 
 <pageFooter>
    <band height="15">
      <textField>
        <reportElement x="0" y="0" width="520" height="15"/>
        <textElement textAlignment="Right"/>
        <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}+"/"]]></textFieldExpression>
      </textField>
      <textField evaluationTime="Report">
        <reportElement x="521" y="0" width="14" height="15"/>
        <textElement textAlignment="Left"/>
        <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression>
      </textField>
    </band>
  </pageFooter>
Note - While using the above code make sure that your footer does not get out of the max report height.

Sample view -

Sample Project -
Sample project can be downloaded from here

You will need maven-3 along with java 5 or higher version, setup in your machine to run the sample.
Kindly follow the below mentioned steps to run the sample and get the report -
  1. Download & unzip the project
  2. Run- mvn clean eclipse:eclipse install in project's home directory
  3. Import the application in eclipse
  4. Execute PageCountFooterTest java file
  5. Sample pdf will be generated at target\\classes\\pageCountFooterTest.pdf location.
References - 
http://salilstock.blogspot.in/2012/05/jasperreport-open-source-java-reporting.html

Friday, May 4, 2012

JasperReport – Open Source Java Reporting Framework


Introduction -
JasperSoft is open source Business Intelligence tool. It comes with below components –
  1. JasperReport Library
  2. JasperReport Server
  3. iReport Designer
  4. JasperSoft Studio
  5. JasperSoft ETL
  6. JasperSoft OLAP

Considering the loose coupling between these components, we can use JasperReport Library to generate reports even at the places where we need to generate reports but do not want to setup complete BI tool.

JasperReport Framework.
JasperReport Framework uses jrxml (a type of xml) language to define the design of reports. The Framework comes with jrxml DTD and four below mentioned fa├žade to help in various phases of report generation –
  1. net.sf.jasperreports.engine.JasperCompileManager – JasperCompileManager provide necessary functions to compile the jrxml to jasper file.
  2. net.sf.jasperreports.engine.JasperFillManager – JasperFillManager provides necessary functions to populate the reports with data from various data sources like database or bean etc
  3. net.sf.jasperreports.engine.JasperPrintManager – JasperPrintManager provides necessary functions to get the populated report printed without exporting to a file.
  4. net.sf.jasperreports.engine.JasperExportManager – JasperExportManager provides necessary function to export the populated reports in various file formats like PDF,  Excel, RTF , HTML, XML, CSV etc

Jasper report lifecycle –
JasperReport life cycle consists of following four steps –

  1. Design (jrxml file creation)
  2. Compile (jasper file creation)
  3. Execute (Filling with Data)
  4. Print/Export

Design (jrxml file creation) – JasperReports can be designed either with creating a jrxml file manually or with available design tool. Design tool way should be preferred as manual creation process would be very time consuming. There are following tools available for designing the repots.
  1. JasperAssistant – JasperAssistant comes as eclipse plug-in. Links to install it can view demo is as mentioned below

  1. JasperWave –JasperWave comes as standalone RCP application as well as eclipse plug-in. Links to install and view the demo is as mentioned below

    Download - http://jasperwave.com/download.html
    JasperWave demo - http://jasperwave.com/docs/gettingStarted.html

  1. JasperSoft Studio - JasperSoft Studio comes as eclipse plug-in. Links to install and get a view is as mentioned below.

    Install  - http://jasperforge.org/website/ireportwebsite/JSS%20Website/plugin_install.html?header=project&target=jaspersoftstudio

    View - https://hanichalouati.wordpress.com/2011/05/10/a-quick-tour-around-japsersoft-studio/
  1. iReports – iReport comes as stand alone application as well as plug-in to NetBeans IDE. Links to install and get a view is as mentioned below

    Download - http://jasperforge.org/website/ireportwebsite/IR%20Website/ir_download.html?header=project&target=ireport

    iReport view - http://jasperforge.org/uploads/publish/ireportwebsite/IR%20Website/ir_getting_started.html

Compile (jasper file creation) - To generate the reports jrxml file needs to compile to jasper file. During the compilation process, following steps is performed.
  1. Validation of jrxml file against the jrxml schema
  2. Creation of java file from jrxml file
  3. Compilation of java file to create the class file.
  4. Creation of object of recently created class file.
  5. Serialize the object to .jasper file.

The object created in step4 works as template during the data filling step of report creation.
Jrxml files can be compiled in various ways as mentioned below –
  1. Compilation through java – net.sf.jasperreports.engine.JasperCompileManager provides necessary functions to compile the jrxml file to jasper file. Compilation should be preferred to be done during the build phase of the project unless the report format keeps on changing in runtime.
  2. Compilation through maven – maven compilation of jasper reports should be preferred in maven projects where the report format is pre-decided and does not change on runtime. Sample example is as mentioned below -
    http://mojo.codehaus.org/jasperreports-maven-plugin/examples/example-1.html
  1. Compilation through ant – ant compilation of the jasper reports should be preferred in the ant projects where the report format is pre-decided and does not change on runtime. Sample example is as mentioned below –

Execution (Filling with Data)
net.sf.jasperreports.engine.JasperFillManager provides necessary functions to fill the data in the reports.

Printing/Exporting
net.sf.jasperreports.engine.JasperPrintManager and net.sf.jasperreports.engine.JasperExportManager provide necessary functions to display print the report/exporting in various file formats.

Sample program –
http://java-bytes.blogspot.in/2009/06/jasper-reports-example.html

Maven dependency to include JasperReports –
JasperReports can be easily integrated into the project using the below dependency –
    
   <dependency>  
     <groupId>net.sf.jasperreports</groupId>  
     <artifactId>jasperreports</artifactId>  
     <version>4.1.2</version>  
   </dependency>  

Maven repository hosting Jasper report –
JasperReports projects build is published at the below location –

References
Jrxml schema reference – http://jasperreports.sourceforge.net/schema.reference.html
Sample report views - http://jasperforge.org/website/ireportwebsite/IR%20Website/ir_gallery.html?header=project&target=ireport
JasperReports Documentation -http://jasperforge.org/website/jasperreportswebsite/trunk/documentation.html?header=project&target=jasperreports
JRXML tag reference - http://jasperforge.org/uploads/publish/jasperreportswebsite/JR%20Website/jasperreports_quickref.html
Jasper Report Ultimate Guide - http://www.rcss.org/publication/newsletter/7178531-The-Jasper-Reports-Ultimate-Guide.pdf

Wednesday, May 2, 2012

HTML2Canvas – JavaScript to capture screenshots of complete or partial page


HTML2Canvas is a JavaScript API to capture full or partial screen shot of page rendered in browser.

It creates the view by traversing the DOM of the webpage. Technically it does not take the screenshot but simulate the view of the web page on the basis of DOM elements and it’s properties. It might not able to generate the proper view of element with CSS elements, which it does not understand.

As different browsers may display the same web page slightly differently, HTML2Canvas will maintain the difference while capturing the screenshot (generating the view).

Advantages
1-     Allows to take partial or full screenshot
2-     Allows can render the screenshot on client without server interaction
3-     Provide mechanism to take on-demand screenshot on the client side
4-     Generates the screenshot as per display of the web page in browser, in which we are taking the screenshot.

Limitations
1-     Pages, which have frames containing pages from sources other than origin of the main page, are not displayed properly. Frames are grayed out.
2-     Many CSS3 properties are not yet supported.
3-     If the page being captured already has canvas element rendering the image from source other than the source of main page, the screenshot would not be able to display the canvas element properly.

Other options

Selenium is other option available in the market to take on demand screenshot on the client side. The key difference between these tools and HTML2Canvas is that these tools work on remote control mechanism and provide us option to remotely control the timing when we want to take the screenshot.

As these tools work on client server model, we will need selenium server running, which would be remotely controlling the client activity.

Selenium is best suited for automation testing than letting user given option to take the capture the screenshot and send on the need basis in the production environment.

Prerequisites
1-     Knowledge of HTML and DOM model
2-     Knowledge of JQuery

Demo application
        http://html2canvas.hertzen.com/screenshots.html

References