Friday, 24 October 2014

Netbeans 8.0 bug "Setter not found for property class (related to JSF 2.2)"

This Exception does not tell where error is / in which file.

Solution is :  <p:outputLabel value="#{msg['header.title']}" class="header" />

use "styleClass"  instead of "class".


FATAL:   JSF1073: java.lang.IllegalArgumentException caught during processing of RENDER_RESPONSE 6 : UIComponent-ClientId=, Message=Setter not found for property class
FATAL:   Setter not found for property class
java.lang.IllegalArgumentException: Setter not found for property class
    at javax.faces.component.UIComponentBase$AttributesMap.put(UIComponentBase.java:2450)
    at javax.faces.component.UIComponentBase$AttributesMap.put(UIComponentBase.java:2330)
    at com.sun.faces.facelets.tag.jsf.ComponentRule$LiteralAttributeMetadata.applyMetadata(ComponentRule.java:87)
    at com.sun.faces.facelets.tag.MetadataImpl.applyMetadata(MetadataImpl.java:81)
    at javax.faces.view.facelets.MetaTagHandler.setAttributes(MetaTagHandler.java:129)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.setAttributes(DelegatingMetaTagHandler.java:102)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.doNewComponentActions(ComponentTagHandlerDelegateImpl.java:412)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:175)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
    at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:189)
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:312)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:371)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:350)
    at com.sun.faces.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:199)
    at com.sun.faces.facelets.tag.ui.IncludeHandler.apply(IncludeHandler.java:120)
    at com.sun.faces.facelets.tag.ui.InsertHandler.apply(InsertHandler.java:116)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:190)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:190)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:190)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:312)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:371)
    at com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:350)
    at com.sun.faces.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:199)
    at com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:169)
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87)
    at com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:161)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.buildView(FaceletViewHandlingStrategy.java:972)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:99)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)

SEVERE:   Error Rendering View[/index.xhtml]
java.lang.ClassCastException: com.sun.faces.facelets.compiler.UIInstructions cannot be cast to org.primefaces.model.menu.MenuElement
    at org.primefaces.component.dock.DockRenderer.encodeMenuItems(DockRenderer.java:74)
    at org.primefaces.component.dock.DockRenderer.encodeMarkup(DockRenderer.java:63)
    at org.primefaces.component.menu.BaseMenuRenderer.encodeEnd(BaseMenuRenderer.java:108)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:924)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:83)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:66)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:81)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:66)
    at org.primefaces.component.layout.LayoutUnitRenderer.encodeEnd(LayoutUnitRenderer.java:49)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:924)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:443)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)

FATAL:   JSF1073: java.lang.ClassCastException caught during processing of RENDER_RESPONSE 6 : UIComponent-ClientId=, Message=com.sun.faces.facelets.compiler.UIInstructions cannot be cast to org.primefaces.model.menu.MenuElement
FATAL:   com.sun.faces.facelets.compiler.UIInstructions cannot be cast to org.primefaces.model.menu.MenuElement
java.lang.ClassCastException: com.sun.faces.facelets.compiler.UIInstructions cannot be cast to org.primefaces.model.menu.MenuElement
    at org.primefaces.component.dock.DockRenderer.encodeMenuItems(DockRenderer.java:74)
    at org.primefaces.component.dock.DockRenderer.encodeMarkup(DockRenderer.java:63)
    at org.primefaces.component.menu.BaseMenuRenderer.encodeEnd(BaseMenuRenderer.java:108)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:924)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:83)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:66)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:81)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:66)
    at org.primefaces.component.layout.LayoutUnitRenderer.encodeEnd(LayoutUnitRenderer.java:49)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:924)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:443)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)

Saturday, 9 August 2014

Guacamole Quick Getting started.

Guacamole( http://guac-dev.org/ )

Introduction
It is web based desktop sharing application.

Components: guacamole-client(war), gucamole-server(guad installable in linux only)
1. guacamole-client is the superproject containing all Maven-based projects that
make Guacamole, an HTML5 web application that provides access to your desktop
using remote desktop protocols.

guacamole-client is used to build the subprojects that make up Guacamole, and
to provide a common central repository. Each project contained here is
completely independent of guacamole-client and can be built separately, though
the others may have to be built first. If all projects are built using
guacamole-client, Maven will take care of the proper build order.

2. The guacamole-server(c/c++) package is a set of software which forms the basis of the
Guacamole stack. It consists of guacd, libguac, and several protocol support
libraries.

guacd is the Guacamole proxy daemon used by the Guacamole web application and
framework. As JavaScript cannot handle binary protocols (like VNC and remote
desktop) efficiently, a new test-based protocol was developed which would
contain a common superset of the operations needed for efficient remote desktop
access, but would be easy for JavaScript programs to process. guacd is the
proxy which translates between arbitrary protocols and the Guacamole protocol.

















Architecture



Install ubuntu 14.04

Setup VNC Server
http://www.howtoforge.com/how-to-install-vnc-server-on-ubuntu-14.04


Installation Guide
The above than 0.8.3 guacamole version are not working for me.

Writing Guacamole application
http://guac-dev.org/doc/0.8.3/gug/writing-you-own-guacamole-app.html

Upgrade Guacamole Steps
sudo service guacd stop
sudo service tomcat6 stop
wget -O guacamole-server-0.9.0.tar.gz http://sourceforge.net/pr...ver-0.9.0.tar.gz/download
tar -xzf guacamole-server-0.9.0.tar.gz
cd guacamole-server-0.9.0/
./configure --with-init-dir=/etc/init.d
make
make install
rm -r /var/lib/tomcat6/webapps/guacamole
cp guacamole-0.9.0.war /var/lib/guacamole/guacamole.war


Wednesday, 26 February 2014

Login Application demo using Spring MVC, JAX-WS, JPA , Hibernate , Mysql

Login Application demo using Spring MVC, JAX-WS, JPA , Hibernate , Mysql

https://github.com/milandashara/Spring-MVC-JAX-WS-JPA-Hibernate-Mysql-Demo
 

Sunday, 16 February 2014

Test Driven Development



Write the tests before development. Gradually correct the failed tests by writing implementation code.

So overall quality of code is good and is according to requirement specification.

It also reduces programmers debugging effort. Tests produced helps in improving readability and understanding of code.

Testing and Good Design are related. So It also improves overall Design.

How To Identify Tests

1. Identify tests with +ve / correct outcome
2. Identify tests with -ve / incorrect outcome
3. Identify tests which may cause exception i.e Destructive tests.

For example , sum(int a,int b) where a,b are +ve integer.
Tests
1. sum(5,7)
2. sum(-5,7)  -ve integer input is invalid
3. sum(null,null) null is not integer

There are various benefits and shortcomings of test drive development. So make sure that it fits proper in your development process before using it.

Monday, 10 February 2014

how to decide to choose abstract class or an interface (Java or .Net)

The abstract class inheritance is used when the subclasses / childs / derived shares the core properties and behaviour of the abstract class. The kind of behaviour that actually defines the class.

On the other hand interface inheritance is used when the classes share peripheral behaviour, ones which do not necessarily define the derived class. It is used to separate implementation and specification. For example , your impl class is called by client using rmi , if there is any change impl class. You are not required to give impl class to client. Client can call impl using specification / interface.



For eg.
Abstract Class : A Car and a Truck shares a lot of core properties and behaviour of an Automobile abstract class,
Interface : They also share some peripheral behaviour like Drillers or PowerGenerators share and doesn't necessarily defines a Car or a Truck, so Car, Truck, Driller and PowerGenerator can all share the same interface IExhaust.

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