What is Static and Dynamic binding in Java with Example

Static and dynamic binding  in Java are two important concept which Java programmer should be aware of. this is directly related to execution of code. If you have more than one method of same name (method overriding) or two variable of same name in same class hierarchy it gets tricky to find out which one is used during runtime as a result of there reference in code. This problem is resolved using static and dynamic binding in Java. For those who are not familiar with binding operation, its process used to link which method or variable to be called as result of there reference in code. Most of the references is resolved during compile time but some references which depends upon Object and polymorphism in Java is resolved during runtime when actual object is available. In this Java tutorial we will see some examples of static and dynamic binding and differences between static binding and dynamic binding in Java.

Dynamic Jasper with Example

Dynamic Jasper Report  – Making dynamic reports easy

DynamicJasper (DJ) is an open source free library that hides the complexity of Jasper Reports, it helps developers to save time when designing simple/medium complexity reports generating the layout of the report elements automatically. DJ creates reports dynamically, defining at runtime the columns, column width (auto width), groups, variables, fonts, charts, crosstabs, sub reports (that can also be dynamic), page size and everything else that you can define at design time.

DJ keeps full compatibility with Jasper Reports since it’s a tool that helps creating reports in a programmatic friendly way, taking care of the report design for you.

Classic .jrxml files can be used as templates while the content and layout of the report elements are handled by the DJ API.

Features

100% pure Java

  • No need to use other tool than you favorite IDE.
  • Friendly and intuitive API.
  • Mature, robust and stable.

Dynamic column report: Columns can be defined at runtime, which means you also control (at runtime) the column positioning, width, title, etc.

Repeating groups / Breaking groups: Create repeating groups dynamically using simple expressions as criteria or complex custom expressions. Each repeating group may have a header and/or footer, which can have a variable showing the result of an operation (SUM, COUNT or any other provided by Jasper Reports).

Automatic report layout: Just define a minimum set of options and DJ will take care of the layout. It’s not an issue to generate the same report for different page sizes and orientation many more!

Dynamic Crosstabs: Jasper Report’s popular crosstabs can now be created dynamically in an easy and convenient way.

Sub reports

  • Sub reports are supported; they can also be dynamically created.
  • Concatenating many reports in a single one (e.g.: a single PDF) can be a hard task. Using DynamicJasper it is really easy get reports of different nature in a single one.

Styles: Each column can have its own style for its title and detail data (defining border, border color, font size, type and color, background color, etc.).

Style library from jrxml files are supported.

Calculation Variables: Repeating groups can have variables that hold the result of an operation on a given field (column). With DJ adding variables is a 1 line of code task.

JRXML template files support: You can use a base template jrxml file in which common styles, company logo, water mark, etc can be pre defined.

Conditional Format: DJ provides a very simple way to define conditional formats. You can use simple conditions or custom conditions.

Auto text: Add auto text in page header and footer such as ?Page 1 of 10?, ?Generated on Oct. 10th 2007? or a custom text.

Charts: Easy to add simple charts.

Barcode columns: As simple as adding a regular column.

Export to most popular formats: As DJ stands over Jasper Reports, it can export to PDF, XML, HTML, CSV, XLS, RTF, TXT.

Clean Excel export: One of the most valuable features that DJ provides is exporting plain reports to excel, with no data formatting, no page break, etc. This is very valuable for end users that use this report to create dynamic tables in Excel, creating these reports just with Jasper Reports can demand a lot of design time.

Integration with popular frameworks:

  • Struts 2 and WebWork are supported out of the box.
  • Grails plug-in is soon to be released.
Example

package com.javamagic.util;

import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperPrint;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import ar.com.fdvs.dj.core.DynamicJasperHelper;
import ar.com.fdvs.dj.core.layout.ClassicLayoutManager;
import ar.com.fdvs.dj.domain.DynamicReport;
import ar.com.fdvs.dj.domain.builders.ReflectiveReportBuilder;

public class DynamicJasperReport extends HttpServlet  {

private static final long serialVersionUID = 1L;

public String getDynamicJasperReport(String query, String title, String fileName, HttpServletResponse resp){

Session session = null;
String result = "";
try {

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();

List list = session.createQuery(query).list();
session.getTransaction().commit();

DynamicReport dynamicReport = new ReflectiveReportBuilder (list).build();
dynamicReport.setTitle(title);

JasperPrint jasperPrint = DynamicJasperHelper.generateJasperPrint(dynamicReport, new ClassicLayoutManager(), list);

resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment;filename=\""+fileName+".pdf\"");

JasperExportManager.exportReportToPdfStream(jasperPrint, resp.getOutputStream());

result = "success";
} catch (Exception e) {
System.out.println("Error : "+e);
result = "error";
} finally {
if (session != null) {
session.close();
}
}

return result;
}

}

Now we can call that  Dynamic Jasper function from any action/servlet.

</pre>
public String getDynamicJasper(){
 String result = "";

try{
 String query = "from ExamPaper";
 String title = "List of Exam Paper";
 String fileName = "ExamPaperList";

DynamicJasperReport  djr = new DynamicJasperReport();

result = djr.getDynamicJasperReport(query, title, fileName, getResponse());
 System.out.println("result : "+result);

}catch(Exception e){
 System.out.println("Error in getDynamicJasper : "+e.getMessage());
 result = "error";
 e.printStackTrace();
 }
 return result;
 }

Hope you will enjoy. Cheers…. 🙂

JAVA / JDK Version History

Java Version History

JDK 1.0 (january 23, 1996) oak
– Initial release

JDK 1.1 (february 19, 1997)
– Retooling of the AWT event model
– Inner classes added to the language
– JavaBeans
– JDBC
– RMI

J2SE 1.2 (December 8, 1998) playground
This and subsequent releases through J2SE 5.0 were rebranded retrospectively Java 2 & version name “J2SE”
(Java 2 platform, Standard edition) replaced JDK to distinguish the base platform from
J2EE (java 2 platform, enterprise edition) and J2ME (java 2 platform, micro edition).

– Strictfp keyword
– Reflection
– Swing api integration into the core classes
– JVM equipped with a jit compiler
– Java plug-in
– Java IDL
– An IDL implementation for corba interoperability
– Collections Framework

J2SE 1.3 (may 8, 2000) kestrel
– Hotspot jvm included
– JavaSound
– JNDI included in core libraries
– Java platform debugger architecture (jpda)
– RMI was modified to support optional compatibility with corba

J2SE 1.4 (february 6, 2002) merlin
– assert keyword
– Regular expressions
– Exception chaining (allows an exception to encapsulate original lower-level exception)
– Internet protocol version 6 (IPV6) support
– Non-blocking nio (new input/output)
– Logging API
– Image i/o api for reading and writing images in formats like jpeg and png
– Integrated XML parser and XSLT processor (JAXP)
– Integrated security and cryptography extensions (JCE, JSSE, JAAS)
– Java web start

J2SE 5.0 (september 30, 2004) tiger [originally numbered 1.5]
– Generics: provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion).
– Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities.
– Autoboxing/unboxing: automatic conversions between primitive types (such as int) and primitive wrapper classes (such as integer).
– Enumerations: the enum keyword creates a typesafe, ordered list of values (such as day.monday, day.tuesday, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern).
– Swing: new skinnable look and feel, called synth.
– Var args: the last parameter of a method can now be declared using a type name followed by three dots (e.g. Void drawtext(string… Lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.
– Enhanced for each loop: the for loop syntax is extended with special syntax for iterating over each member of either an array or any iterable, such as the standard collection classesfix the previously broken semantics of the java memory model, which defines how threads interact through memory.
– Automatic stub generation for rmi objects.
– Static imports concurrency utilities in package java.util.concurrent.
– Scanner class for parsing data from various input streams and buffers.
– Assertions
– StringBuilder class (in java.lang package)
– Annotations

Java SE 6 (december 11, 2006) mustang
sun replaced the name “J2SE” with java se and dropped the “.0” from the version number.
Beta versions were released in february and june 2006, leading up to a final release that occurred on december 11, 2006.
The current revision is update 14 which was released in may 2009.

– Support for older win9x versions dropped.
– Scripting lang support: Generic API for integration with scripting languages, & built-in mozilla javascript rhino integration
– Dramatic performance improvements for the core platform, and swing.
– Improved web service support through JAX-WS JDBC 4.0 support
– Java compiler API: an API allowing a java program to select and invoke a java compiler programmatically.
– Upgrade of JAXB to version 2.0: including integration of a stax parser.
– Support for pluggable annotations
– Many GUI improvements, such as integration of swingworker in the API, table sorting and filtering, and true swing double-buffering (eliminating the gray-area effect).

Java se 6 update 10
A major enhancement in terms of end-user usability.
– Java Deployment Toolkit, a set of javascript functions to ease the deployment of applets and java web start applications.
– Java Kernel, a small installer including only the most commonly used jre classes. Enhanced updater.
– Enhanced versioning and pack200 support: server-side support is no longer required.
– Java quick starter, to improve cold start-up time.
– Improved performance of java2D graphics primitives on windows, using direct3D and hardware acceleration.
– A new Swing look and feel called NIMBUS and based on synth.
– Next-generation java plug-in: applets now run in a separate process and support many features of web start applications.

Java se 6 update 12
This release includes the highly anticipated 64-bit java plug-in (for 64-bit browsers only), windows server 2008 support,
and performance improvements of java and JAVAFX applications.

 

Java SE 7

  • Swing
  • IO and New IO
  • Networking
  • Security
  • Concurrency Utilities
  • Rich Internet Applications (RIA)/Deployment
    • Requesting and Customizing Applet Decoration in Dragg able Applets
    • Embedding JNLP File in Applet Tag
    • Deploying without Codebase
    • Handling Applet Initialization Status with Event Handlers
  • Java 2D
  • Java XML – JAXP, JAXB, and JAX-WS
  • Internationalization
  • java.lang Package
    • Multithreaded Custom Class Loaders in Java SE 7
  • Java Programming Language
    • Binary Literals
    • Strings in switch Statements
    • The try-with-resources Statement
    • Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
    • Underscores in Numeric Literals
    • Type Inference for Generic Instance Creation
    • Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
  • Java Virtual Machine (JVM)
    • Java Virtual Machine Support for Non-Java Languages
    • Garbage-First Collector
    • Java HotSpot Virtual Machine Performance Enhancements
  • JDBC

 

 

Hippo CMS – a Java Open Source Web Content Management Solutions

Hippo CMS is an open-source information centered Content Management System. The Hippo CMS project was initiated and is maintained by Hippo. It’s targeted at medium to large organisations managing content for multi-channel distribution like web sites and intranets. It facilitates an open and flexible way of using your information by following international accepted open standards.

Hippo is a Java Open Source Web Content Management system that enables a true, open and context-aware content strategy.

Hippo CMS is a Java Open Source Web content management (WCM) solution that drives high performance Web properties. Hippo’s focus is to enable organizations to empower audiences to consume content on their terms.

Open Source and Open Standards

Hippo CMS is user friendly, has an open architecture and is designed for interoperability with existing environments. Hippo CMS is built to integrate external sources of content into one. Therefore, it uses all relevant open standards to allow this integration. For many existing sources, connectors are available in the codebase.

The open architecture of Hippo CMS has the following key points:

  • Faceted repository
  • Open source
  • Content repository API for Java, JSR-170
  • Works with open standards
  • Reuse of content
  • Separation of content, design, logic and the CMS itself.
  • User friendly user interface
  • Native XML, 100% Java
  • No vendor lock-in

Hope you will enjoy this. Cheers… 😉

KonaKart – a java eCommerce system

KonaKart is a java eCommerce system aimed at medium to large online retailers. The KonaKart product is owned by DS Data Systems UK Ltd with staff in Italy and the UK.

KonaKart provides an extensive set of features to enable retailers to successfully sell their products over the internet. It is a Java / JSP / XML based solution with easy to use java APIs and a SOAP Web Service interface that allow retailers to quickly integrate eCommerce functionality into existing systems. The customizable parts of KonaKart are Open Source and available under the GNU LGPL.

KonaKart includes both a Storefront application and an AJAX-enabled Administration Application. The Administration Application includes role-based security which allows companies to define the administrative functions that should be allowed for different user groups.

Features :

  • Comprehensive eCommerce / shopping cart functionality
  • Ease of integration through its complete set of java, SOAP, JSON and RMI APIs
  • Ease of creation of unique storefronts by using the jQuery / javascript libraries
  • Ease of customization – with examples, tutorials and source code available
  • High performance, scalability and reliability
  • Ability to run as a JSR-168 portlet – eg in Liferay
  • Wide choice of supported databases (MySQL, Oracle, PostgreSQL, DB2, MS SQL Server)

The Community Edition of is free and can be downloaded from the KonaKart website.

Hope you will enjoy this. Cheers.. 😉

Read, Write Excel With Java – POI

Apache POI project consists of APIs for manipulating various file formats such as Open Office XML (ECMA-376) and Microsoft’s OLE 2 Compound Document formats using pure Java. It provides pure Java libraries for reading and writing files in Microsoft Office formats, such as Word, PowerPoint and Excel. POI supports the ISO/IEC 29500:2008 Office Open XML file formats since version 3.5.

Apache-POI’s XSSF component can read .xlsx files. JExcel only supports the older .xls file format.

Apache-POI also offers an event based API which can be used to drastically reduce the memory footprint when reading but using it is more complicated than just reading the file directly.

Write Excel With Java – POI


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;

public class PoiWriteExcelFile {

public static void main(String[] args) {
try {
FileOutputStream fileOut = new FileOutputStream("test.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("Worksheet");

HSSFRow row = worksheet.createRow((short) 0);

HSSFCell cellA1 = row.createCell(0);
cellA1.setCellValue("Hello");
HSSFCellStyle styleOfCell = workbook.createCellStyle();
styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);
cellA1.setCellStyle(styleOfCell);

HSSFCell cellB1 = row.createCell(1);
cellB1.setCellValue("World");
styleOfCell = workbook.createCellStyle();
styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);
cellB1.setCellStyle(styleOfCell);

HSSFCell cellC1 = row.createCell(2);
cellC1.setCellValue("Happy");
styleOfCell = workbook.createCellStyle();
styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);
cellC1.setCellStyle(styleOfCell);

HSSFCell cellD1 = row.createCell(3);
cellD1.setCellValue(new Date());
styleOfCell = workbook.createCellStyle();
styleOfCell.setDataFormat(HSSFDataFormat
.getBuiltinFormat("m/d/yy h:mm"));
styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);
cellD1.setCellStyle(styleOfCell);

row = worksheet.createRow(1);
row.createCell(0).setCellValue(Calendar.getInstance().getTime().toString());
row.createCell(1).setCellValue("a string");
row.createCell(2).setCellValue(true);
row.createCell(3).setCellType(Cell.CELL_TYPE_ERROR);

workbook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}

Read Excel With Java – POI


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class PoiReadExcelFile {
public static void main(String[] args) {
try {
FileInputStream iStream = new FileInputStream("test.xls");
HSSFWorkbook workbook = new HSSFWorkbook(iStream);
HSSFSheet worksheet = workbook.getSheet("Worksheet");
//get first row
HSSFRow row = worksheet.getRow(0);
HSSFCell cellA1 = row.getCell(0);
System.out.println("A1 "+cellA1.getStringCellValue());
HSSFCell cellB1 = row.getCell(1);
System.out.println("B1 "+cellB1.getStringCellValue());
HSSFCell cellC1 = row.getCell(2);
System.out.println("C1 "+cellC1.getStringCellValue());
HSSFCell cellD1 = row.getCell(3);
System.out.println("D1 "+cellD1.getDateCellValue());
//get next row
row = worksheet.getRow(1);
HSSFCell cellA2 = row.getCell(0);
System.out.println("A2 "+cellA2.getStringCellValue());
HSSFCell cellB2 = row.getCell(1);
System.out.println("B2 "+cellB2.getStringCellValue());
HSSFCell cellC2 = row.getCell(2);
System.out.println("C2 "+cellC2.getBooleanCellValue());
HSSFCell cellC3 = row.getCell(3);
System.out.println("D2 "+cellC3.getErrorCellValue());

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

OUTPUT :

A1 Hello
B1 World
C1 Happy
D1 Sat Dec 31 08:55:00 IST 2011
A2 Sat Dec 31 08:55:00 IST 2011
B2 a string
C2 true
D2 15

Hope you will like this. Cheers… 😉

JFreeChart – Java chart library

JFreeChart is the most widely used chart library for Java, By using JFreeChart library that makes it easy for developers to display professional quality charts in their applications.

JFreeChart is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications

JFreeChart’s extensive feature set includes:

  • Consistent and well-documented API, supporting a wide range of chart types;
  • Flexible design that is easy to extend, and targets both server-side and client-side applications;
  • Support for many output types, including Swing components, image files (including PNG and JPEG), and vector graphics file formats (including PDF, EPS and SVG); JFreeChart is “open source” or, more specifically, free software. It is distributed under the terms of the GNU Lesser General Public Licence (LGPL), which permits use in proprietary applications.

It supports following type of charts

  • X-Y charts (line, spline and scatter). Time axis is possible.
  • Pie charts
  • Gantt charts
  • Bar charts (horizontal and vertical, stacked and independent). It also has built-in histogram plotting.
  • Single valued (thermometer, compass, speedometer) that can then be placed over map.
  • Various specific charts (wind chart, polar chart, bubbles of varying size, etc).

JFreeChart Example


import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.util.Rotation;


public class JFreeChartExample extends JFrame {

private static final long serialVersionUID = 1L;

public JFreeChartExample(String applicationTitle, String chartTitle) {
super(applicationTitle);
//Creates a sample dataset
DefaultPieDataset dataSet = new DefaultPieDataset();
dataSet.setValue("Chrome", 29);
dataSet.setValue("InternetExplorer", 36);
dataSet.setValue("Firefox", 35);

// based on the dataset we create the chart
JFreeChart pieChart = ChartFactory.createPieChart3D(chartTitle, dataSet, true, true, false);
PiePlot plot = (PiePlot) pieChart.getPlot();
plot.setStartAngle(290);
plot.setDirection(Rotation.CLOCKWISE);
plot.setForegroundAlpha(0.5f);

// Adding chart into a chart panel
ChartPanel chartPanel = new ChartPanel(pieChart);

// settind default size
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));

// add to contentPane
setContentPane(chartPanel);
}
public static void main(String[] args) {
JFreeChartExample chart = new JFreeChartExample("Browser Usage Statistics", "Which Browser are you using?");
chart.pack();
chart.setVisible(true);
}
}

OUTPUT :

Hope you will like this. Cheers… 🙂

Parsing/Reading RSS/Atom Feed Using ROME

ROME library contains utility classes for parsing and publishing syndicated feeds, it is an open source Java library that make it easy to work with RSS/Atom feeds.

Rome library have converters to convert from one format to another. Rome can parse any format of Newsfeed, including RSS variants and Atom.

It will support most of the syndication formats includes following

  1. RSS 0.90
  2. RSS 0.91 Netscape
  3. RSS 0.91 Userland
  4. RSS 0.92
  5. RSS 0.93
  6. RSS 0.94
  7. RSS 1.0
  8. RSS 2.0
  9. Atom 0.3
  10. Atom 1.0

Note : Download ROME and JDOM

Parsing/Reading RSS/Atom Example


import java.net.URL;
import java.util.Iterator;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class Reader {

public static void main(String[] args) throws Exception {

URL url  = new URL("https://javamagic.wordpress.com/feed/");
XmlReader reader = null;

try {

reader = new XmlReader(url);
SyndFeed feed = new SyndFeedInput().build(reader);
System.out.println("Feed Title: "+ feed.getAuthor());

for (Iterator i = feed.getEntries().iterator(); i.hasNext();) {
SyndEntry entry = (SyndEntry) i.next();
System.out.println(entry.getTitle());
}
} finally {
if (reader != null)
reader.close();
}
}
}

Hope you will like this. Cheers.. 🙂

Create Sitemap Using Java

Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling.

Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site.

Web crawlers usually discover pages from links within the site and from other sites. Using the Sitemap protocol does not guarantee that web pages are included in search engines, but provides hints for web crawlers to do a better job of crawling your site. Sitemap 0.90 has wide adoption, including support from Google, Yahoo!, and Microsoft.

It will also support for google site map updations.

Note : sitemapgen4j-1.0.1.jar – Set in classpath

SitemapGen4j Features

SitemapGen4j is a library to generate XML sitemaps in Java.

  • Adding any number of URLs
  • Can set gzipped output
  • Can set lastmod option
  • Can set priority option
  • Can set changefreq option
  • Configuring the date format
  • Configuring sitemap index file
  • Validate your sitemaps against official XML Schema Definition (XSD)

Create Sitemap Using SitemapGen4j


import java.io.File;
import java.net.MalformedURLException;
import java.util.Date;

import com.redfin.sitemapgenerator.ChangeFreq;
import com.redfin.sitemapgenerator.WebSitemapGenerator;
import com.redfin.sitemapgenerator.WebSitemapUrl;

public class SitemapGenerator {

public static void main(String[] args) throws MalformedURLException {
// If you need gzipped output
WebSitemapGenerator wsg = WebSitemapGenerator.builder("http://www.javamagic.wordpress.com", new File("C:\\sitemap"))
.gzip(true).build();

WebSitemapUrl url = new WebSitemapUrl.Options("https://javamagic.wordpress.com/2012/02/24/create-pdf-with-itext-java-tutorial/")
.lastMod(new Date()).priority(1.0).changeFreq(ChangeFreq.HOURLY).build();
// this will configure the URL with lastmod=now, priority=1.0, changefreq=hourly

//You can add any number of urls here
wsg.addUrl(url);
wsg.addUrl("https://javamagic.wordpress.com/2011/12/16/prototype-pattern/");
wsg.write();
}
}

Hope you will like this. Cheers… 🙂

Create PDF With iText Java Tutorial

Creating PDF with java in enterprise applications is quite common these days.

iText is a free and open source library for creating and manipulating PDF files in Java. It was written by Bruno Lowagie, Paulo Soares, and others. It enables developers looking to enhance web and other applications with dynamic PDF document generation and/or manipulation.

Note : itext-5.1.2.jar – Set in classpath to access and make pdf.

Developers can use iText to:

  • Serve PDF to a browser
  • Generate dynamic documents from XML files or databases
  • Use PDF’s many interactive features
  • Add bookmarks, page numbers, watermarks, etc.
  • Split, concatenate, and manipulate PDF pages
  • Automate filling out of PDF forms
  • Add digital signatures to a PDF file

Text is used in projects that have one of the following requirements:

  • The content isn’t available in advance: it’s calculated based on user input or real-time database information.
  • The PDF files can’t be produced manually due to the massive volume of content: a large number of pages or documents.
  • Documents need to be created in unattended mode, in a batch process.
  • The content needs to be customized or personalized; for instance, the name of the end user has to be stamped on a number of pages.

Create PDF With iText


import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class CreatePDFWithItext{

public static void main(String[] args) {
try {
OutputStream file = new FileOutputStream(new File("C:\\example.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
document.add(new Paragraph("Hello World"));
document.add(new Paragraph("http://www.javamagic.wordpress.com/"));
document.add(new Paragraph(new Date().toString()));
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Hope you will like this. Cheers… 🙂