Friday 13 September 2013

Struts 2 Jasper integration using maven

1. maven dependencies need
<dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>5.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-jasperreports-plugin</artifactId>
            <version>2.3.15.1</version>
        </dependency>

2. Sample POJO Class
package com.doctorAppointment.action;

public class DoctorDetail {

    private String firstname;
   
    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getScheduleAppointment() {
        return scheduleAppointment;
    }

    public void setScheduleAppointment(String scheduleAppointment) {
        this.scheduleAppointment = scheduleAppointment;
    }

    public String getDoctor() {
        return doctor;
    }

    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    private String lastname;
   
    private String scheduleAppointment;
   
    private String doctor;
   
    private String comments;
}

3. Sample jasper_template.jrxml : template design of document generated using jasper
<?xml version="1.0"?>
<!DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="jasper_test" language="java">
  <!-- Our fields from the DoctorDetail class. -->
  <field name="firstname" class="java.lang.String"/>
  <field name="lastname" class="java.lang.String"/>
  <field name="doctor" class="java.lang.String"/>
  <field name="comments" class="java.lang.String"/>
  <field name="scheduleAppointment" class="java.lang.String"/>
  <title>
    <band height="50">
      <staticText>
        <reportElement x="0" y="0" width="180" height="15"/>
        <textElement/>
        <text><![CDATA[Appointment]]></text>
      </staticText>
    </band>
  </title>
  <pageHeader>
    <band/>
  </pageHeader>
  <columnHeader>
    <band height="20">
      <staticText>
        <reportElement x="0" y="0" width="90" height="20"/>
        <textElement>
          <font isUnderline="true"/>
        </textElement>
        <text><![CDATA[FIRST NAME]]></text>
      </staticText>
      <staticText>
        <reportElement x="90" y="0" width="90" height="20"/>
        <textElement>
          <font isUnderline="true"/>
        </textElement>
        <text><![CDATA[LASTNAME]]></text>
      </staticText>
    
       <staticText>
        <reportElement x="180" y="0" width="90" height="20"/>
        <textElement>
          <font isUnderline="true"/>
        </textElement>
        <text><![CDATA[SCHEDULE APPOINTMENT]]></text>
      </staticText>
       <staticText>
        <reportElement x="270" y="0" width="90" height="20"/>
        <textElement>
          <font isUnderline="true"/>
        </textElement>
        <text><![CDATA[DOCTOR]]></text>
      </staticText>
       <staticText>
        <reportElement x="360" y="0" width="90" height="20"/>
        <textElement>
          <font isUnderline="true"/>
        </textElement>
        <text><![CDATA[COMMENTS]]></text>
      </staticText>
    </band>
  </columnHeader>
  <detail>
    <band height="20">
      <textField>
        <reportElement x="0" y="0" width="180" height="15"/>
        <textElement/>
        <textFieldExpression><![CDATA[$F{firstname}]]></textFieldExpression>
      </textField>
      <textField>
        <reportElement x="90" y="0" width="180" height="15"/>
        <textElement/>
        <textFieldExpression><![CDATA[$F{lastname}]]></textFieldExpression>
      </textField>
      <textField>
        <reportElement x="180" y="0" width="180" height="15"/>
        <textElement/>
        <textFieldExpression><![CDATA[$F{scheduleAppointment}]]></textFieldExpression>
      </textField>
      <textField>
        <reportElement x="270" y="0" width="180" height="15"/>
        <textElement/>
        <textFieldExpression><![CDATA[$F{doctor}]]></textFieldExpression>
      </textField>
      <textField>
        <reportElement x="360" y="0" width="180" height="15"/>
        <textElement/>
        <textFieldExpression><![CDATA[$F{comments}]]></textFieldExpression>
      </textField>
    </band>
  </detail>
  <columnFooter>
    <band/>
  </columnFooter>
  <pageFooter>
    <band height="15">
      <staticText>
        <reportElement x="0" y="0" width="40" height="15"/>
        <textElement/>
        <text><![CDATA[Page:]]></text>
      </staticText>
      <textField>
        <reportElement x="40" y="0" width="100" height="15"/>
        <textElement/>
        <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression>
      </textField>
    </band>
  </pageFooter>
  <summary>
    <band/>
  </summary>
</jasperReport>

4. Compile .jrxml to .jasper on context initialization of web application. One time compilation is only needed : .jasper is used by jasper reported to convert in various format like HTML,PDF,XLS etc


try {
            JasperCompileManager.compileReportToFile(jrxmlFilePath,
                    contextFolder + "\\compiled_template.jasper");
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
 Action Class
package com.doctorAppointment.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperCompileManager;

import org.apache.struts2.ServletActionContext;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.docx4j.XmlUtils;
import org.docx4j.convert.in.xhtml.XHTMLImporter;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.NumberingDefinitionsPart;
import org.docx4j.openpackaging.parts.WordprocessingML.StyleDefinitionsPart;
import org.docx4j.wml.Style;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.opensymphony.xwork2.Action;

public class PrintDocumentAction implements Action {

    /*
     * private InputStream fileInputStream;
     *
     * public InputStream getFileInputStream() { return fileInputStream; }
     */
    /** List to use as our JasperReports dataSource. */
    private List<DoctorDetail> myList;

    public List<DoctorDetail> getMyList() {
        return myList;
    }

    @Override
    public String execute() throws Exception {
        System.out.println("PrintPDF start");

        HttpServletRequest request = ServletActionContext.getRequest();
        String contextFolder = request.getServletContext().getRealPath("");
        String jrxmlFilePath = contextFolder + "\\jasper_template.jrxml";

        myList = new ArrayList<DoctorDetail>();
        myList.add((DoctorDetail) request.getSession().getAttribute(
                "doctorDetail"));

     
        return "SUCCESS";
    }

}
 
5. Struts.xml
<package name="jasper" namespace="/" extends="jasperreports-default">
        <result-types>
            <result-type
                class="org.apache.struts2.views.jasperreports.JasperReportsResult"
                name="jasper">
            </result-type>
        </result-types>
        <action name="documentDownload" class="com.doctorAppointment.action.PrintDocumentAction">

            <result name="SUCCESS" type="jasper">
                <param name="contentType">application/pdf</param>
                <param name="location">compiled_template.jasper</param>
                <param name="dataSource">myList</param>
                <param name="format">PDF</param>
                    <param name="contentDisposition">attachment;filename="doctorAppointment.pdf"</param>
                <param name="bufferSize">1024</param>
            </result>
        </action>
    </package> 


Full Source : https://github.com/milandashara/struts2-jasper-yahp-demo.git

Thursday 12 September 2013

HTML to PDF using Java

1. Grab html source using javascript function

function getPageHTML(){ 
                return "<html>" + document.getElementsByTagName('html')[0].innerHTML + "</html>";
            }
2. Post this html source as parameter using jquery on click of pdfDownload.
printPDF is relative url i.e http:localhost:8080/Demo/printPDF

htmlString is post request parameter

$("#pdfDownload").click(function() {
                //alert("Handler for .click() called.");

                var fullHtml = getPageHTML();

                $.post("printPDF", {
                    htmlString : fullHtml
                   
                });

            });

3. Save html source to .html file and convert html to pdf using YAHP Converter. Here is example of action class of struts2.
package com.doctorAppointment.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.allcolor.yahp.converter.CYaHPConverter;
import org.allcolor.yahp.converter.IHtmlToPdfTransformer;
import org.apache.struts2.ServletActionContext;

public class PrintPDF {

    private InputStream fileInputStream;

    public InputStream getFileInputStream() {
        return fileInputStream;
    }

    // configure fopFactory as desired
    // private final FopFactory fopFactory = FopFactory.newInstance();

    /** xsl-fo namespace URI */
    protected static String foNS = "http://www.w3.org/1999/XSL/Format";

    public String execute() throws Exception {

        System.out.println("PrintPDF start");
        HttpServletRequest request = ServletActionContext.getRequest();
        String html = request.getParameter("htmlString");
        String contextFolder = request.getServletContext().getRealPath("");

        String htmlFileName = contextFolder + "\\download.html";
        String pdfFileName = contextFolder + "\\download.pdf";

        File htmlFile = new File(htmlFileName);
        if (htmlFile.exists()) {
            htmlFile.delete();
            htmlFile.createNewFile();
        } else {
            htmlFile.createNewFile();
        }
        // save html
        FileWriter htmlFileWriter = new FileWriter(htmlFile);
        htmlFileWriter.write(html);
        htmlFileWriter.flush();
        htmlFileWriter.close();

        // File pdfFile=new File(pdfFileName);

        // new converter
        CYaHPConverter converter = new CYaHPConverter();
        // save pdf in outfile
        File fout = new File(pdfFileName);
        FileOutputStream out = new FileOutputStream(fout);
        // contains configuration properties
        Map properties = new HashMap();
        // list containing header/footer
        List headerFooterList = new ArrayList();
        // add header/footer
        headerFooterList
                .add(new IHtmlToPdfTransformer.CHeaderFooter(
                        "<table width=\"100%\"><tbody><tr><td align=\"left\">"
                                + "Generated with YaHPConverter.</td><td align=\"right\">Page <pagenumber>/<"
                                + "pagecount></td></tr></tbody></table>",
                        IHtmlToPdfTransformer.CHeaderFooter.HEADER));
        headerFooterList.add(new IHtmlToPdfTransformer.CHeaderFooter(
                "© 2009 Quentin Anciaux",
                IHtmlToPdfTransformer.CHeaderFooter.FOOTER));
        properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS,
                IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
        // properties.put(IHtmlToPdfTransformer.FOP_TTF_FONT_PATH, fontPath);

        converter.convertToPdf(htmlFile.toURI().toURL(),
                IHtmlToPdfTransformer.A4P, headerFooterList, out, properties);

        out.flush();
        out.close();

        fileInputStream = new FileInputStream(fout);
        return "SUCCESS";
    }

}

Required YAHP maven dependency
<dependency>
            <groupId>com.google.code.maven-play-plugin.org.allcolor.yahp</groupId>
            <artifactId>yahp</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.maven-play-plugin.org.allcolor.yahp</groupId>
            <artifactId>yahp-internal</artifactId>
            <version>1.3-patched-play-pdf-0.8</version>
        </dependency>

Source : https://github.com/milandashara/struts2-jasper-yahp-demo.git

Note : Download may not run from eclipse. It will work after deploying war in tomcat

Thursday 18 July 2013

Few Important Design Patterns

Few Important Design Patterns

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

Creational Design Patterns

1. Abstract factory :

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Example

interface Button is
  method paint()

interface GUIFactory is
  method createButton()
      output:  a button

class WinFactory implementing GUIFactory is
  method createButton() is
      output:  an Windows button
    Return a new WinButton

class OSXFactory implementing GUIFactory is
  method createButton() is
      output:  an OS X button
    Return a new OSXButton

class WinButton implementing Button is
  method paint() is
    Render a button in a Windows style

class OSXButton implementing Button is
  method paint() is
    Render a button in a Mac OS X style

class Application is
  constructor Application(factory) is
      input:  the GUIFactory factory used to create buttons
    Button button := factory.createButton()
    button.paint()

Read the configuration file
If the OS specified in the configuration file is Windows, then
  Construct a WinFactory
  Construct an Application with WinFactory
else
  Construct a OSXFactory
  Construct an Application with OSXFactory
 
 
2. Factory method
 
Define an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses

The benefit is that the client code (calling code) can just say "give me an object that can do XYZ" without knowing what is the actual class that can do "XYZ".

3. Singleton

Ensure a class has only one instance, and provide a global point of access to it.

Lazy initialization
This method uses double-checked locking, which should not be used prior to J2SE 5.0, as it is vulnerable to subtle bugs. The problem is that an out-of-order write may allow the instance reference to be returned before the Singleton constructor is executed.[9]
public class SingletonDemo {
        private static volatile SingletonDemo instance = null;
 
        private SingletonDemo() {       }
 
        public static SingletonDemo getInstance() {
                if (instance == null) {
                        synchronized (SingletonDemo .class){
                                if (instance == null) {
                                        instance = new SingletonDemo ();
                                }
                      }
                }
                return instance;
        }
}
Eager initialization
If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization, which always creates an instance:
public class Singleton {
    private static final Singleton instance = new Singleton();
 
    private Singleton() {}
 
    public static Singleton getInstance() {
        return instance;
    }
}
This method has a number of advantages:
  • The instance is not constructed until the class is used.
  • There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.
  • The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.
Static block initialization
Some authors[10] refer to a similar solution allowing some pre-processing (e.g. for error-checking). In this sense, the traditional approach could be seen as a particular case of this one, as the class loader would do exactly the same processing.
public class Singleton {
  private static final Singleton instance;
 
  static {
    try {
      instance = new Singleton();
    } catch (IOException e) {
      throw new RuntimeException("Darn, an error occurred!", e);
    }
  }
 
  public static Singleton getInstance() {
    return instance;
  }
 
  private Singleton() {
    // ...
  }
} 
 
The solution of Bill Pugh
 The technique known as the initialization on demand holder idiom, is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines. The nested class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that getInstance() is called. Thus, this solution is thread-safe without requiring special language constructs (i.e. volatile or synchronized).

public class Singleton {
        // Private constructor prevents instantiation from other classes
        private Singleton() { }
 
     /**
     * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
     * or the first access to SingletonHolder.INSTANCE, not before.
     */
        private static class SingletonHolder { 
                public static final Singleton INSTANCE = new Singleton();
        }
 
        public static Singleton getInstance() {
                return SingletonHolder.INSTANCE;
        }
} 
 
Behavioural Design Pattern

1. Adapter / Wrapper / Translator Patter
 
 It translates one interface for a class into a compatible interface.
 An adapter helps two incompatible interfaces to work together. 
Implementation of Adapter pattern
When implementing the adapter pattern, for clarity use the class name [AdapteeClassName]To[Interface]Adapter, for example DAOToProviderAdapter. It should have a constructor method with adaptee class variable as parameter. This parameter will be passed to the instance member of [AdapteeClassName]To[Interface]Adapter.
public class AdapteeToClientAdapter implements Client {
 
    private final Adaptee instance;
 
    public AdapteeToClientAdapter(final Adaptee instance) {
         this.instance = instance;
    }
 
    @Override
    public void clientMethod() {
       // call Adaptee's method(s) to implement Client's clientMethod
    }
 
} 
 
2. Decorator pattern
 
Decorator design pattern is used to enhance the functionality of a particular object at run-time or 
dynamically.

JDK use decorator pattern in IO package where it has decorated Reader and Writer Classes for various 
scenario, for example BufferedReader and BufferedWriter are example of decorator design pattern in 
Java.
 
3.  Facade


Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
 
Example
This is an abstract example of how a client ("you") interacts with a facade (the "computer") to a complex system (internal computer parts, like CPU and HardDrive).

/* Complex parts */
 
class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}
 
class Memory {
    public void load(long position, byte[] data) { ... }
}
 
class HardDrive {
    public byte[] read(long lba, int size) { ... }
}
 
/* Facade */
 
class Computer {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;
 
    public Computer() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }
 
    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }
}
 
/* Client */
 
class You {
    public static void main(String[] args) {
        Computer facade = new Computer();
        facade.start();
    }
} 
 
4. Front Controller

The pattern relates to the design of Web applications. It provides a centralized entry point for handling requests.
 
Example : Struts 2 framework





  

Wednesday 17 July 2013

Digital Signature

Purpose

It is used by receiver to authenticate sender of message. There is no way to authenticate public key of sender in digital signature. Solution for this is use of certificates.

Key generation Algorithm(DSA) and specification(example X.509 standard) at sender and receiver side should be same.

Signing data and verify signature should use same message digest(example SH1) at both side.

Steps at message sender side

1. Generate public,private key using DSA Algorithm

2. Generate Signature : Use private key,message digest(SH1) and message to generate signature.

Message Digest
A Message Digest is a digitally created hash (fingerprint) created from a plaintext block. All the information of the message is used to construct the Message Digest hash, but the message cannot be recovered from the hash. For this reason, Message Digests are also known as one way hash functions.

The size of a Message Digest is always the same, independent of the size or content of the message from which it was created. Generally, the size of a Message Digest is fairly short ( 1024 bits). The ideal Message Digest algorithm would possibly alter 50% of the bits in the resulting hash if one bit was altered in the plaintext message. 

3.  Save message, public key in byte, and signature in bytes in file and  Send it to receiver.

Steps at message receiver side

1. Get public key from public key file send by sender. Algorithm used for decoding key from bytes should be same as sender key generation algorithm

2. Verify signature using public key , message. Message Digest used should be same as sender.