Pages

Friday, 4 October 2013

Example of mail merge generating multiple files.

Example of mail merge (Dependency Example) generating different files using RTFTemplate library.


  • Add required JARS in class path.
  •  Required JARS:  
       
     rtftemplate-1.0.1-b14.jar  
     commons-collections-3.2.1.jar  
     spring-beans-3.2.2.RELEASE.jar  
     spring-context-3.2.2.RELEASE.jar  
     spring-context-support-3.2.2.RELEASE.jar  
     spring-core-3.2.2.RELEASE.jar  
     spring-expression-3.2.2.RELEASE.jar  
     spring-jdbc-3.2.2.RELEASE.jar  
     spring-orm-3.2.2.RELEASE.jar  
     spring-tx-3.2.2.RELEASE.jar  
     xml-apis-1.0.b2.jar  
     commons-logging-1.1.1.jar  
     freemarker.jar  
     commons-digester-2.1.jar  
     org.apache.commons.beanutils.jar  
     velocity-1.7.jar  
     commons-lang.jar  
    
package com.rtf.impl;
public class Dependency {
private String artifactID;
private String type;
private String version;
private String url;
public Dependency(String artifactID, String type, String version, String url) {
this.artifactID = artifactID;
this.type = type;
this.version = version;
this.url = url;
}
public String getArtifactID() {
return artifactID;
}
public void setArtifactID(String artifactID) {
this.artifactID = artifactID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
view raw Dependency hosted with ❤ by GitHub
package com.rtf.impl;
import java.util.ArrayList;
import java.util.Collection;
public class Developer {
private String name;
private String email;
private Collection<Role> roles;
private Manager manager;
public Developer(String name, String email) {
this.name = name;
this.email = email;
roles = new ArrayList<Role>();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
public void addRole(Role role) {
roles.add(role);
}
public void addRole(String roleName) {
addRole(new Role(roleName));
}
public Manager getManager() {
return manager;
}
public void setManager(Manager manager) {
this.manager = manager;
}
}
view raw Developer hosted with ❤ by GitHub
package com.rtf.impl;
public class DeveloperGroup {
private Developer developer1;
private Developer developer2;
private Developer developer3;
public DeveloperGroup(Developer developer1, Developer developer2,
Developer developer3) {
this.developer1 = developer1;
this.developer2 = developer2;
this.developer3 = developer3;
}
public Developer getDeveloper1() {
return developer1;
}
public void setDeveloper1(Developer developer1) {
this.developer1 = developer1;
}
public Developer getDeveloper2() {
return developer2;
}
public void setDeveloper2(Developer developer2) {
this.developer2 = developer2;
}
public Developer getDeveloper3() {
return developer3;
}
public void setDeveloper3(Developer developer3) {
this.developer3 = developer3;
}
}
view raw DeveloperGroup hosted with ❤ by GitHub
package com.rtf.impl;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.rtf.RTFTemplate;
import net.sourceforge.rtf.helper.RTFTemplateBuilder;
/**
* This class is to generate a multiple file with there different addresses
* using RTF Template.
*
* @author Suraj Bhambhani
*
*/
public class GenerateMultipleRTFFiles {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
// Source of file to be generated.
String rtfSource = "src/RTF_Websites.rtf";
// 1. Get default RTFtemplateBuilder
RTFTemplateBuilder builder = RTFTemplateBuilder.newRTFTemplateBuilder();
// 2. Get RTFtemplate with default Implementation of template engine
RTFTemplate rtfTemplate = builder.newRTFTemplate();
// 3. Set the RTF model source
rtfTemplate.setTemplate(new File(rtfSource));
// List of Projects
List<Project> projects = new ArrayList<Project>();
// Project with one website, website2 exists.
Project project1 = new Project("Be Open Source", "Suraj Bhambhani",
"OutOfMemory", "", "www.scart.com");
// Project with two website.
Project project2 = new Project("Be Open Source", "Suraj Bhambhani",
"OutOfMemory", "www.liveinSF.com", "www.liveinNJ.com");
// Project with one website, website1 exists.
Project project3 = new Project("Be Open Source", "Suraj Bhambhani",
"OutOfMemory", "www.workwithme.com", "");
// Project with one website, website1 exists.
Project project4 = new Project("Be Open Source", "Suraj Bhambhani",
"OutOfMemory", "www.workinSF.com", "www.workinNJ.com");
projects.add(project1);
projects.add(project2);
projects.add(project3);
projects.add(project4);
rtfTemplate.put("header_developer_name", "Name");
rtfTemplate.put("header_developer_email", "Email");
rtfTemplate.put("header_developer_roles", "Roles");
// Dependencies
List<Dependency> dependencies = new ArrayList<Dependency>();
Dependency dependency = new Dependency("commons-collection", "jar",
"1.0", "http://jakarta.apache.org/commons/collection/");
dependencies.add(dependency);
rtfTemplate.put("dependencies", dependencies);
// List of developers.
List<Developer> developers = new ArrayList<Developer>();
Developer developer;
developer = new Developer("Will Glass-Husain", "wglass@apache.org");
developer.addRole("Java Developer");
developer.addRole("Manager");
rtfTemplate.put("developers", developers);
developers.add(developer);
developer = new Developer("Ma-Husain", "wglass@apache.org");
developer.addRole("Java Developer");
developer.addRole("Manager");
developers.add(developer);
// Iterating over projects and generating files accordingly.
for (Project projectIterate : projects) {
// When both wesite exists.
if (!projectIterate.getWebsite1().equals("")
&& !projectIterate.getWebsite2().equals("")) {
withTwoWebsites(rtfTemplate, projectIterate);
withTwoWebsites(rtfTemplate, projectIterate);
}
// When Website2 exists and website1 not.
if (projectIterate.getWebsite1().equals("")
&& !projectIterate.getWebsite2().equals("")) {
withWebsite2(rtfTemplate, projectIterate);
}
// When Website1 exists and website2 not.
if (!projectIterate.getWebsite1().equals("")
&& projectIterate.getWebsite2().equals("")) {
withWebsite1(rtfTemplate, projectIterate);
}
System.out.println(projectIterate.getWebsite1());
System.out.println(projectIterate.getWebsite2());
}
}
private static void withWebsite1(RTFTemplate rtfTemplate,
Project projectIterate) throws Exception {
String name;
name = projectIterate.getWebsite1();
generateFile(rtfTemplate, projectIterate, name);
}
private static void withWebsite2(RTFTemplate rtfTemplate,
Project projectIterate) throws Exception {
String name;
projectIterate.setWebsite1(projectIterate.getWebsite2());
name = projectIterate.getWebsite2();
generateFile(rtfTemplate, projectIterate, name);
}
private static void generateFile(RTFTemplate rtfTemplate,
Project projectIterate, String name) throws Exception {
// 4. Put the context.
rtfTemplate.put("project", projectIterate);
String rtfTarget = "Project_" + name + ".rtf";
// 5. Merge the RTF source model and the context
rtfTemplate.merge(rtfTarget);
}
private static void withTwoWebsites(RTFTemplate rtfTemplate,
Project projectIterate) throws Exception {
String name;
boolean websiteCheck = true;
int websitBreak = 0;
// When two website exist.
while (true) {
name = projectIterate.getWebsite1();
if (websiteCheck == false) {
projectIterate.setWebsite1(projectIterate.getWebsite2());
name = projectIterate.getWebsite2();
}
generateFile(rtfTemplate, projectIterate, name);
websitBreak++;
websiteCheck = false;
if (websitBreak == 2)
break;
}
}
}
package com.rtf.impl;
import java.util.ArrayList;
import java.util.List;
public class Manager {
private List<Project> projects;
public Manager(String name) {
this.name = name;
this.projects = new ArrayList<Project>();
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addProject(Project project) {
projects.add(project);
}
public List<Project> getProjects() {
return projects;
}
}
view raw Manager hosted with ❤ by GitHub
package com.rtf.impl;
import java.io.InputStream;
import java.util.List;
public class Project {
private String name;
private InputStream logo = null;
private String clientName;
private String error;
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
private String website1;
private String website2;
public String getWebsite2() {
return website2;
}
public void setWebsite2(String website1) {
this.website2 = website1;
}
public String getWebsite1() {
return website1;
}
public void setWebsite1(String website) {
this.website1 = website;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public Project(String name, String clientName, String error,
String website, String website1) {
this.name = name;
this.clientName = clientName;
this.error = error;
this.website1 = website;
this.website2 = website1;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setLogo(InputStream logo) {
this.logo = logo;
}
public InputStream getLogo() {
return logo;
}
private List<Project> group;
public List<Project> getGroup() {
return group;
}
public void addProject(Project project) {
group.add(project);
}
}
view raw Project hosted with ❤ by GitHub
package com.rtf.impl;
public class Role {
private String name;
public Role(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
view raw Role hosted with ❤ by GitHub
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- **********************************************************************
********************* RTFTEMPLTE IMPLEMENTATION *********************
********************************************************************** -->
<!-- Defautlt RTFTemplate implementation with freemarker template engine -->
<bean id="ftlRTFTemplate"
class="net.sourceforge.rtf.RTFTemplate"
singleton="false" >
<property name="parser" ref="defaultRTFParser" />
<property name="transformer" ref="ftlTransformer" />
<property name="templateEngine" ref="ftl" />
</bean>
<!-- Defautlt RTFTemplate implementation with velocity template engine -->
<bean id="vmRTFTemplate"
class="net.sourceforge.rtf.RTFTemplate"
singleton="false" >
<property name="parser" ref="defaultRTFParser" />
<property name="transformer" ref="vmTransformer" />
<property name="templateEngine" ref="vm" />
</bean>
<!-- **********************************************************************
********************* RTFDOCUMENT PARSER *********************
********************************************************************** -->
<!-- Defautlt RTFDocument Parser -->
<bean id="defaultRTFParser"
class="net.sourceforge.rtf.handler.RTFDocumentHandler"
singleton="true" >
</bean>
<!-- **********************************************************************
********************* FREEMARKER TEMPLATE ENGINE *********************
********************************************************************** -->
<!-- Freemarker template engine -->
<bean id="ftl"
class="net.sourceforge.rtf.template.freemarker.FreemarkerTemplateEngineImpl"
singleton="false" >
<property name="freemarkerConfiguration" ref="ftlConfiguration" />
</bean>
<!-- Freemarker Configuration -->
<bean id="ftlConfiguration"
class="freemarker.template.Configuration"
singleton="true" >
</bean>
<!-- Freemarker RTF Document Transformer -->
<bean id="ftlTransformer"
class="net.sourceforge.rtf.template.freemarker.RTFFreemarkerTransformerImpl"
singleton="true" >
</bean>
<!-- **********************************************************************
********************* VELOCITY TEMPLATE ENGINE *********************
********************************************************************** -->
<bean id="vm"
class="net.sourceforge.rtf.template.velocity.VelocityTemplateEngineImpl"
singleton="false" >
<property name="velocityEngine" ref="vmEngine" />
</bean>
<!-- VelocityEngine Configuration -->
<bean id="vmEngine"
class="org.apache.velocity.app.VelocityEngine"
singleton="true" >
</bean>
<!-- Velocity RTF Document Transformer -->
<bean id="vmTransformer"
class="net.sourceforge.rtf.template.velocity.RTFVelocityTransformerImpl"
singleton="true" >
</bean>
</beans>


References:-
http://sourceforge.net/projects/rtftemplate/

http://rtftemplate.sourceforge.net/

Thursday, 3 October 2013

Example of mail Merging

Example of mail Merging (Address Example) using RTFTemplate library.


  • Add required JARS in class path.
  •  Required JAR:  
       
     commons-collections-3.2.1.jar  
     commons-digester-2.1.jar  
     commons-lang.jar  
     commons-logging-1.1.1.jar  
     freemarker.jar  
     org.apache.commons.beanutils.jar  
     rtftemplate-1.0.1-b14.jar  
     spring-beans-3.2.2.RELEASE.jar  
     spring-context-3.2.2.RELEASE.jar  
     spring-context-support-3.2.2.RELEASE.jar  
     spring-core-3.2.2.RELEASE.jar  
     spring-expression-3.2.2.RELEASE.jar  
     spring-tx-3.2.2.RELEASE.jar  
     velocity-1.7.jar  
     xml-apis-1.0.b2.jar  
    
  • Download the RTF sample and Template file in rtf format.
  • Add the required classes.

package com.sb.rtf;
public class Address {
private String typeOfAddress;
private String address;
private int pinCode;
public int getPinCode() {
return pinCode;
}
public void setPinCode(int pinCode) {
this.pinCode = pinCode;
}
public String getTypeOfAddress() {
return typeOfAddress;
}
public void setTypeOfAddress(String typeOfAddress) {
this.typeOfAddress = typeOfAddress;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Address(String typeOfAddress, String address, int i) {
super();
this.typeOfAddress = typeOfAddress;
this.address = address;
this.pinCode = i;
}
}
view raw Address hosted with ❤ by GitHub
package com.sb.rtf;
import java.util.List;
public class ContractPartner {
private final String businessPartnerName;
private final List<Address> businessPartnerAddreses;
private final String businessPartnerWebsite;
private final List<Partner> partners;
private final List<Role> roles;
private final String contractWith;
public String getBusinessPartnerName() {
return businessPartnerName;
}
public List<Address> getBusinessPartnerAddreses() {
return businessPartnerAddreses;
}
public String getBusinessPartnerWebsite() {
return businessPartnerWebsite;
}
public ContractPartner(String businessPartnerName,
List<Address> businessPartnerAddreses,
String businessPartnerWebsite, List<Partner> partners,
String contractWith,List<Role> roles) {
super();
this.businessPartnerName = businessPartnerName;
this.businessPartnerAddreses = businessPartnerAddreses;
this.businessPartnerWebsite = businessPartnerWebsite;
this.partners = partners;
this.contractWith = contractWith;
this.roles = roles;
}
public List<Partner> getPartners() {
return partners;
}
public String getContractWith() {
return contractWith;
}
public List<Role> getRoles() {
return roles;
}
}
view raw ContractPartner hosted with ❤ by GitHub
package com.sb.rtf;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ContractPartnerProvider {
@SuppressWarnings("unchecked")
public static List<ContractPartner> getBusinessPartner()
throws SQLException {
List<ContractPartner> contractPartner = new ArrayList<ContractPartner>();
List<Address> adresses = new ArrayList<Address>();
Address address = new Address("Work",
"540, Kalbadevi Rd, Wagh wadi, Kalbadevi Mumbai 022 6622 5454",
400096);
adresses.add(address);
address = new Address("Home",
"640 , Wagh wadi, Kalbadevi Mumbai 022 6622 5454", 401090);
adresses.add(address);
List<Role> roles =new ArrayList<Role>();
roles.add(new Role("Editor"));
roles.add(new Role("writer"));
roles.add(new Role("Author"));
ContractPartner bp = new ContractPartner("Suraj Bhambhani", adresses,
"www.sbit.com",getPartner(), "SB IT Solutions",roles);
contractPartner.add(bp);
return contractPartner;
}
public static List<Partner> getPartner() {
List<Partner> partners = new ArrayList<Partner>();
Partner partner = new Partner("Susen", "susen@gmail.com", "Instructor");
partners.add(partner);
partner = new Partner("Saush", "saushh@gmail.com", "Super Instructor");
partners.add(partner);
return partners;
}
}
package com.sb.rtf;
public class Partner {
private String partnerName;
private String partnerEmail;
private String partnerRole;
public String getPartnerName() {
return partnerName;
}
public void setPartnerName(String partnerName) {
this.partnerName = partnerName;
}
public String getPartnerEmail() {
return partnerEmail;
}
public void setPartnerEmail(String partnerEmail) {
this.partnerEmail = partnerEmail;
}
public String getPartnerRole() {
return partnerRole;
}
public void setPartnerRole(String partnerRole) {
this.partnerRole = partnerRole;
}
public Partner(String partnerName, String partnerEmail, String partnerRole) {
super();
this.partnerName = partnerName;
this.partnerEmail = partnerEmail;
this.partnerRole = partnerRole;
}
}
view raw Partner hosted with ❤ by GitHub
package com.sb.rtf;
public class Role {
private final String role;
public Role(String role) {
this.role = role;
}
public String getRole() {
return role;
}
}
view raw Role hosted with ❤ by GitHub
package com.sb.rtf;
import java.io.File;
import java.io.FileNotFoundException;
import net.sourceforge.rtf.RTFTemplate;
import net.sourceforge.rtf.UnsupportedRTFTemplate;
import net.sourceforge.rtf.helper.RTFTemplateBuilder;
public class RTFHandler {
public static String getRTFTemplateSource(String rtfSource) {
return rtfSource;
}
public static RTFTemplate getRTFTemplate(String rtfSource)
throws UnsupportedRTFTemplate, FileNotFoundException {
// 1. Get default RTFtemplateBuilder
RTFTemplateBuilder builder = RTFTemplateBuilder.newRTFTemplateBuilder();
// 2. Get RTFtemplate with default Implementation of template engine
RTFTemplate rtfTemplate = builder.newRTFTemplate();
// 3. Set the RTF model source
rtfTemplate.setTemplate(new File(rtfSource));
return rtfTemplate;
}
public static void putList(RTFTemplate rtfTemplate,String source,Object object) {
rtfTemplate.put(source,object );
}
public static void putData(RTFTemplate rtfTemplate,String source,String destination) {
rtfTemplate.put(source, destination);
}
public static void generateFiles(RTFTemplate rtfTemplate,
String name) throws Exception {
// 4. Put the context.
String rtfTarget = "Contract_" + name + ".rtf";
// 5. Merge the RTF source model and the context
rtfTemplate.merge(rtfTarget);
}
public static void generateFile(RTFTemplate rtfTemplate, String string) throws Exception {
String rtfTarget = "Project_.rtf";
// 5. Merge the RTF source model and the context
rtfTemplate.merge(rtfTarget);
}
}
view raw RTFHandler hosted with ❤ by GitHub
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- **********************************************************************
********************* RTFTEMPLTE IMPLEMENTATION *********************
********************************************************************** -->
<!-- Defautlt RTFTemplate implementation with freemarker template engine -->
<bean id="ftlRTFTemplate"
class="net.sourceforge.rtf.RTFTemplate"
singleton="false" >
<property name="parser" ref="defaultRTFParser" />
<property name="transformer" ref="ftlTransformer" />
<property name="templateEngine" ref="ftl" />
</bean>
<!-- Defautlt RTFTemplate implementation with velocity template engine -->
<bean id="vmRTFTemplate"
class="net.sourceforge.rtf.RTFTemplate"
singleton="false" >
<property name="parser" ref="defaultRTFParser" />
<property name="transformer" ref="vmTransformer" />
<property name="templateEngine" ref="vm" />
</bean>
<!-- **********************************************************************
********************* RTFDOCUMENT PARSER *********************
********************************************************************** -->
<!-- Defautlt RTFDocument Parser -->
<bean id="defaultRTFParser"
class="net.sourceforge.rtf.handler.RTFDocumentHandler"
singleton="true" >
</bean>
<!-- **********************************************************************
********************* FREEMARKER TEMPLATE ENGINE *********************
********************************************************************** -->
<!-- Freemarker template engine -->
<bean id="ftl"
class="net.sourceforge.rtf.template.freemarker.FreemarkerTemplateEngineImpl"
singleton="false" >
<property name="freemarkerConfiguration" ref="ftlConfiguration" />
</bean>
<!-- Freemarker Configuration -->
<bean id="ftlConfiguration"
class="freemarker.template.Configuration"
singleton="true" >
</bean>
<!-- Freemarker RTF Document Transformer -->
<bean id="ftlTransformer"
class="net.sourceforge.rtf.template.freemarker.RTFFreemarkerTransformerImpl"
singleton="true" >
</bean>
<!-- **********************************************************************
********************* VELOCITY TEMPLATE ENGINE *********************
********************************************************************** -->
<bean id="vm"
class="net.sourceforge.rtf.template.velocity.VelocityTemplateEngineImpl"
singleton="false" >
<property name="velocityEngine" ref="vmEngine" />
</bean>
<!-- VelocityEngine Configuration -->
<bean id="vmEngine"
class="org.apache.velocity.app.VelocityEngine"
singleton="true" >
</bean>
<!-- Velocity RTF Document Transformer -->
<bean id="vmTransformer"
class="net.sourceforge.rtf.template.velocity.RTFVelocityTransformerImpl"
singleton="true" >
</bean>
</beans>
package com.sb.rtf;
import java.util.List;
import net.sourceforge.rtf.RTFTemplate;
/**
* This class is to generate a sample contract using RTF Template.
* @author Suraj Bhambhani
*
*/
public class SampleContractGenerator {
public static void main(String[] args) throws Exception {
// Source of file to be generated.
String rtfSource = "ContractTemplate.rtf";
// Generate template.
RTFTemplate rtfTemplate = RTFHandler.getRTFTemplate(rtfSource);
// Business Partner
List<ContractPartner> contractPartners = ContractPartnerProvider
.getBusinessPartner();
// Generate file.
generateFile(rtfTemplate, contractPartners);
// Desktop.getDesktop().open(new File("Contract_Example.rtf"));
}
private static void generateFile(RTFTemplate rtfTemplate,
List<ContractPartner> contractPartners) throws Exception {
RTFHandler.putList(rtfTemplate, "businessPartner",
(ContractPartner) contractPartners.get(0));
RTFHandler.generateFiles(rtfTemplate, "SB IT Solution");
}
}
References:-
http://sourceforge.net/projects/rtftemplate/

http://rtftemplate.sourceforge.net/

Wednesday, 4 September 2013

Mail merge functionality using RTF template file.

Overview

RTFTemplate is RTF engine RTF to RTF, which is able to generate RTF by merging template RTF (model RTF  source) with JAVA object (context). RTFTemplate use Velocity for  merging template  with JAVA object.

Steps to Merge RTF template and Java Context:


  • Step Parse RTF model source (1) consist to load RTF model source into RTFDocument structure .RTFDocument contains the whole RTF model, which split RTF elements interpretated by RTFTemplate as fields (RTFField), bookmarks (RTFBookmark)...
  • Step Transform RTF Document (2) consist to transform the RTFDocument structure, in other words:
    1. replace RTF code with specific macro swith template engine selected (ex : replace bookmark with#foreach macro when RTFTemplate is used with Velocity).
    2. remove some RTF code. For merge fields (MERGEFIELD), RTFTemplate remove the character " which include merge fields.









Steps for office Integration

  • RTF  template  can  be  created  with  MS  Word  by,  using MERGEFIELD,  HYPERLINK and BOOKMARK (cf. RTF specification).
  • This template will be merged with  Java objects  (can be  from database, LDAP etc.) and RTF  file will be generated at particular target.
  • These files can be saved in RTF as well as PDF format.
  • The generated files can be printed or send by email.



References:-
http://sourceforge.net/projects/rtftemplate/

http://rtftemplate.sourceforge.net/

Examples.

Address example.
Dependency example.



Friday, 23 August 2013

Steps to install JBOSS 7.1.1 sever.

  1.     Download the Binary zip files from http://labs.jboss.com/jbossas/downloads/.
  2.     In this form of installation, simply un-zip the downloaded zip file to the directory of your choice on any operating system that supports the zip format.
  3.     Go-to --> <Current Directory>\jboss-as-7.1.1.Final\bin
  4.     Run the run.bat file for setting JBOSS_HOME  
  5.     Now for starting JBoss server run <JBOSS_HOME>\bin\standalone.bat file and server will be in running mode.


Friday, 9 August 2013

Comparison between Flyway and Liquibase

Comparison between Flyway and Liquibase


Features supported by Liquibase
  1. Liquibase XML: - Smallest common denominator DB-independent format. It frees you from writing DDL and is compatible across DBs. Vendor lock-in (may or may not be an issue).
  2. Liquibase annotated SQL: - SQL with Liquibase metadata in comments (must be present). DDL gets converted to Liquibase XML with custom SQL blocks at runtime. May or may not be compatible across DBs.
  3. Refactoring: - All database change modelled as a "refactoring". Makes rollback feasible.
  4. SQL Scripts: - Generation of SQL scripts for DBA review.
  5. Multiple Databases: - Liquibase supports multiples databases; It has the option to describe your changes in a database-neutral manner so the same upgrade script can be used with multiple database types.
  6. Execution: - Conditional execution of changesets (based on DBcontext, or whether the changeset has been altered).

Features supported by Flyway

  1. Plain SQL: - Regular DDL SQL file. May or may not be compatible across DBs. No special annotations. DB structure dumps using native DB tools may be used as is. No tool specific constructs. No lock in.
  2. Procedures/Functions: - It support DB dumps including PL/SQL, T-SQL or MySQL and PostgreSQL stored procedures.
  3. Java migrations: - Migrations are Java classes using the JDBC API. Great for dealing with LOBs and complex data transformations. May or may not be compatible across DBs. Vendor lock-in (may or may not be an issue).
  4. Convention Over Configuration: - Classpath Scanning to automatically discover Sql and Java migrations.
  5. Highly reliable: - Safe for cluster environments (Multiple machines can migrate in parallel).
  6. Cloud support: - Runs on Google App Engine with full support for Google Cloud SQL.
  7. Auto-migration on Startup: - Ship migrations together with the application and run them automatically on startup using the API.
  8. Fail fast: - Inconsistent database or failed migration prevents app from starting.
  9. Schema Clean: - Drop all tables, views, triggers, from a schema without dropping the schema itself

Summary
  • FlyWay is "lower level" with you specifying exactly the SQL you want ran whereas Liquibase is "higher level" with you specifying what you want changed and Liquibase computing the SQL.
  • FlyWay manages changes by filename whereas Liquibase manages changes by order in a file.

References:-
http://stackoverflow.com/questions/8418814/db-migration-tool-liquibase-or-flyway

Please find below the link for feature comparison:-

Friday, 12 July 2013

How to build a maven project job in Jenkins


How to build a maven project job in Jenkins


 Creating new job.



  • Select a New Job from the left menu bar.
  • Add the Job name specified in red box.
  • Select the radio button for building a maven2/3 project.
  • Click Ok.

 Configuring Project 


  • Add the Repository URL by selecting the Subversion (SVN) button.
  •  If you want to specify the folder name where all build process should be done, it can be entered in Local module directory.

Specifying the goals and Options.



  • You can set goals you want to execute followed by the Database options  -DDBUsername=<DB Username> -DDBPassword=<DB Password> -DDBUrl=<Database URL>”.
  • Click Save and Apply.                                                                                                                                                
References:-



Why to use Jenkins for CRON jobs.

Why Jenkins

Jenkins is an application which monitors executions of repeated jobs, such as building a software project or jobs run by cron.
  • Building/testing software projects continuously, just like CruiseControl or DamageControl. In a nutshell, Jenkins provides an easy-to-use so-called continuous integration system, making it easier for developers to integrate changes to the project, and making it easier for users to obtain a fresh build. The automated, continuous build increases the productivity.
  • Monitoring executions of externally-run jobs, such as cron jobs and procmail jobs, even those that are run on a remote machine. For example, with cron, all you receive is regular e-mails that capture the output, and it is up to you to look at them diligently and notice when it broke. Jenkins keeps those outputs and makes it easy for you to notice when something is wrong. 

Meet Jenkins
Jenkins can be installed as:
  1. It can be installed as a windows service.
  2. Its war can be run through a command prompt.


Using Jenkins


Challenges in Jenkins

·       JUnit through Ant Script

When JUnit is run through Ant script, if you want to display the results in Jenkins, it is important the reports generated should be in XML format, because Jenkins only reads in XML format.

·       Memory leakage problem when JUnit is run through Maven.

Refer this link to resolve the problem.

References:




Thursday, 11 July 2013

Difference between Spring Batch & Quartz Scheduler

Difference between Spring Batch & Quartz:

 Spring Batch and Quartz  have different goals. Spring Batch provides functionality for processing large volumes of data and Quartz provides functionality for scheduling tasks. So Quartz could complement Spring Batch, but are not excluding technologies. A common combination would be to use Quartz as a trigger for a Spring Batch job using a Cron expression and the Spring Core convenience SchedulerFactoryBean

Spring Batch Features

The first stable build was  released in January 30, 2009 (Ver. 1.1.4) ,From many years it is used by many companies.

                Spring Batch is a lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems. Spring Batch builds upon the productivity, POJO-based development approach, and general ease of use capabilities people have come to know from the Spring Framework, while making it easy for developers to access and leverage more advanced enterprise services when necessary.

Benefits of Using Spring Batch

  • Since the foundation of Spring Batch is based upon the Spring framework, you also get all of the benefits of Spring such as dependency injection and bean management based upon simple POJOs.
  • For developers already accustomed to developing Spring based applications, it’s a very short ramp up time getting familiar with using the Spring Batch framework.
  • The majority of the technical aspects surrounding the creation of batch applications have been solved and the developer instead spends more time solving the business needs.
  • By leveraging the additional functionality of Spring Integration, you can further increase the scalability of more distributed processes.


 
Quartz Features

Runtime Environments:
  • Quartz can run embedded within another free standing application
  • Quartz can be instantiated within an application server (or servlet container), and participate in XA transactions
  • Quartz can run as a stand-alone program (within its own Java Virtual Machine), to be used via RMI
  • Quartz can be instantiated as a cluster of stand-alone programs (with load-balance and failover capabilities)


Job Scheduling:
       Jobs are scheduled to run when a given Trigger occurs. Triggers can be created with nearly any combination of the following directives:

  • at a certain time of day (to the millisecond)
  • on certain days of the week
  • on certain days of the month
  • on certain days of the year
  • not on certain days listed within a registered Calendar (such as business holidays)
  • repeated a specific number of times
  • repeated until a specific time/date
  • repeated indefinitely
  • repeated with a delay interval
  • Jobs are given names by their creator and can also be organized into named groups. Triggers may also be given names and placed into groups, in order to easily organize them within the scheduler. Jobs can be added to the scheduler once, but registered with multiple Triggers. Within an enterprise Java environment, Jobs can perform their work as part of a distributed (XA) transaction.



Job Execution:

  •  Jobs can be any Java class that implements the simple Job interface, leaving infinite possibilities for the work your Jobs can perform.
  •  Job class instances can be instantiated by Quartz, or by your application's framework.
  • When a Trigger occurs, the scheduler notifies zero or more Java objects implementing the JobListener and TriggerListener interfaces (listeners can be simple Java objects, or EJBs, or JMS publishers, etc.). These listeners are also notified after the Job has executed.
  •  As Jobs are completed, they return a JobCompletionCode which informs the scheduler of success or failure. The JobCompletionCode can also instruct the scheduler of any actions it should take based on the success/fail code - such as immediate re-execution of the Job.


Job Persistence:

  •  The design of Quartz includes a JobStore interface that can be implemented to provide various mechanisms for the storage of jobs.
  • With the use of the included JDBCJobStore, all Jobs and Triggers configured as "non-volatile" are stored in a relational database via JDBC.
  • With the use of the included RAMJobStore, all Jobs and Triggers are stored in RAM and therefore do not persist between program executions - but this has the advantage of not requiring an external database.


Transactions:

  • Quartz can participate in JTA transactions, via the use of JobStoreCMT (a subclass of JDBCJobStore).
  • Quartz can manage JTA transactions (begin and commit them) around the execution of a Job, so that the work performed by the Job automatically happens within a JTA transaction.


Clustering:

  • Failover.
  • Load balancing.
  • Quartz's built-in clustering features rely upon database persistence via JDBCJobStore (described above).
  • Terracotta extensions to Quartz provide clustering capabilities without the need for a backing database.


Listeners & Plug-Ins:

  • Applications can catch scheduling events to monitor or control job/trigger behavior by implementing one or more listener interfaces.
  • The Plug-In mechanism can be used add functionality to Quartz, such keeping a history of job executions, or loading job and trigger definitions from a file.
  • Quartz ships with a number of "factory built" plug-ins and listeners.


Summary

 Quartz is a full-featured, open source job scheduling service that can be integrated with, or used alongside virtually any Java application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components that may execute virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as support for JTA transactions and clustering.

Who is using Quartz?

Quartz is in use by many thousands of entities, many of whom have directly embedded Quartz in their own custom applications, and others who are using products that already have Quartz embedded within them.

Quartz 1.6.0 was directly downloaded more than 100,000 times, and countless additional times through secondary repositories (such as ibiblio.org).

Here is a list of just a few of the thousands of Quartz users:
  • Vodafone Ireland - uses Quartz for scheduling tests to be carried out on systems in order to generate quality of service information.
  •  Covalent Technologies, Inc. - uses Quartz within their CAM product to handle anything scheduling related in the system, such as: scheduling server actions (start, restart, etc.), metric calculations, data cleanup daemons, etc.
  • Partnet Inc. - uses Quartz for scheduling application events and driving workflows within many of its products. Partnet has been a contributor to the Quartz code base in years past.
  • U.S. Department of Defense - uses Quartz at various points within a large electronic commerce application, notably order fulfillment.
  • Level3 Communications - uses Quartz to drive software builds and deployments.
  • Atlassian - uses Quartz within several of their excellent products, such as JIRA and Confluence.
  • Cisco - uses Quartz in various in-house systems.
  • Apache Jakarta - Quartz is used within (or as plugins to) several products falling under the Jakarta umbrella.
  • OpenSymphony - Uses Quartz to drive the OS Workflow product.
  • Spring - Quartz is used within the Spring Framework.
  • XpoLog - uses Quartz within XpoLog Center in order to enable automatic technical support.
  • Bloombase Technologies - has integrating Quartz within their Spitfire EAI Server for XML security processing.
  • Thomson Tax and Accounting - uses Quartz in its job scheduling framework within it's editorial systems group.
  • The Liferay Portal - is using the Quartz Scheduler. Just download and check the code. Liferay Inc. Portal.
  • Infoglue CMS - from infoglue.org
  • Apache Cocoon - uses Quartz to provide scheduling features and to run application background processes.
  • JBoss - uses Quartz for the implementation of a number of services within its infrastructure.
  • Adobe - uses Quartz for scheduling database operations in their LiveCycle Enterprise Suite.
  • Icebergsofts - uses Quartz for job scheduling in iceQA 2009.
  • Cypress Care Inc. - uses Quartz for all Insurance-related Job Scheduling for the organization
  • OpenReports - (http://oreports.com) - an open source web reporting application uses Quartz to schedule reports.
  • Ubik-Ingenierie - (http://www.ubik-ingenierie.com) uses Quartz in an in house Batch server for Java.
  • Apache Synapse - uses Quartz to add Job Scheduling to the Apache Synapse ESB. It is also being "inherited" by the WSO2 ESB which is another Open Source project that packages Apache Synapse.
  • Sun's OpenESB community - uses Quartz for the Scheduler component in the ESB that can be used in conjunction with a growing list of 40+ components such as RSS, FTP, SAP, CORBA, scripting engines, event processing, business process orchestration, etc.
  • Caucho - uses Quartz to power the scheduling features within their Resin Java EE 6 Web Profile implementation.
  • Adeptia - uses Quartz to provide scheduling and job management features within its Adeptia Suite line of ETL, Integration and Business Process Management products.
  • OpenSearchServer - (http://www.open-search-server.com) uses Quartz to provide scheduling features.



References:-

Spring Batch API



Quartz API

How to create DOCX file using DOX4J api using Java.

How to read the Word Template?


  1. A docx file is merely a zip-archive of xml files (plus any binary files for embedded objects such as images), we met that requirement by unpacking the zip file, feeding the document.xml to a template engine that does the merging for us, and then zipping the output document to get the new docx file.
  2. If we want to generate a doc file either Apache POI jar can be used but, how to read the xml & write in doc file or Jasper which reads the xml file and write to doc file. 
  3. Docx to docx conversion can be done by feeding the values in XML and save it by using docx4J jar.




What DOX4J can do?


  • Open existing docx (from filesystem, SMB/CIFS, WebDAV using VFS), pptx, xlsx.
  • Create new docx, pptx, xlsx.
  • Programmatically manipulate the above (of course) Specific to docx4j (as opposed to pptx4j, xlsx4j).
  • Template substitution; CustomXML binding.
  • Produce/consume Word 2007's xmlPackage (pkg) format.
  • Save docx to filesystem as a docx (ie zipped), or to JCR (unzipped).
  • Apply transforms, including common filters.
  • Export as HTML or PDF.
  • Difference/Compare documents, paragraphs or sdt (content controls).
  • Font support (font substitution, and use of any fonts embedded in the document).




Problems with Apache POI:-

Apache POI's HWPF can read .doc files, and docx4j could use this for basic conversion of .doc to .docx.
The problem with this approach is that POI's HWPF code fails on many .doc files.

What Approach we can use?

An effective approach is to use OpenOffice (via jodconverter) to convert the doc to docx, which docx4j
can then process. If you need to return a binary .doc, OpenOffice/jodconverter can convert the docx back to .doc.

There is also http://b2xtranslator.sourceforge.net/ . If a pure Java approach were required, this could be converted.



Some References : -

How to open and manipulate Word document/template in Java?

http://stackoverflow.com/questions/9379580/how-to-open-and-manipulate-word-document-templatein-java

Getting started with DOCX4J.
http://www.docx4java.org/svn/docx4j/trunk/docx4j/docs/Docx4j_GettingStarted.html

Working with Apache POI.
http://poi.apache.org/

Example awaited.