Saturday, August 17, 2013

Perform CRUD Operation's MongoDB with Java.


MongoDB :

Data in MongoDB has a flexible schemaCollections do not enforce document structure. This means that:

  • documents in the same collection do not need to have the same set of fields or structure, and
  • common fields in a collection’s documents may hold different types of data.

Each document only needs to contain relevant fields to the entity or object that the document represents. In practice, most documents in a collection share a similar structure. Schema flexibility means that you can model your documents in MongoDB so that they can closely resemble and reflect application-level objects. For more information Click on that link.

Requirements : 

  1. Download MongoDB from here.
  2. Install MongoDB and set the PATH variable . 
  3. Install JDK 7 (The following code is Tested On JDK 7.

Note: Before Running the code, Need to start MongoDB server .


Following is the CODE to perform CRUD operation's of MongoDB with JAVA.

import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Date;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.QueryBuilder;
import com.mongodb.ServerAddress;

public class MongoDBCRUDOperationInJava {
 public static void main(String[] args) throws UnknownHostException {
  MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));
  DB courseDB = client.getDB("students");
  DBCollection collection = courseDB.getCollection("grades");
  //collection.drop();
  //insertDocument(collection);
  //findOne(collection);
  //findAll(collection);
  //count(collection);
  //findWithCriteriaUsingDBObject(collection);
  findWithCriteriaUsingQueryBuilder(collection);
}

public static void insertDocument(DBCollection collection) {
 DBObject doc = new BasicDBObject("_id", new ObjectId());
 doc.put("name", "Harmeet");
 doc.put("age", 24);
 doc.put("birthday", new Date(12312312313l));
 doc.put("programmer", true);
 doc.put("language", Arrays.asList("Java", "Scala", "Python"));
 doc.put("address", new BasicDBObject("street", "5").append("area", "moga"));
 DBObject doc2 = new BasicDBObject().append("name", "Jimmy");
System.out.println("Before Inserting the Document in Collection : "+doc);
 collection.insert(Arrays.asList(doc, doc2));
 System.out.println("After Inserting the Document in Collection : "+doc);
}
public static void findOne(DBCollection collection) {
 DBObject doc = collection.findOne();
 System.out.println(doc);
}
public static void findAll(DBCollection collection) {
 DBCursor cur = collection.find();
 try{
   while(cur.hasNext()){
   DBObject doc = cur.next();
   System.out.println(doc);
  }
 }finally{
 cur.close();
 }
}
public static void count(DBCollection collection) {
 System.out.println("COunt of collection Documents : "+collection.count());
}
public static void findWithCriteriaUsingDBObject(DBCollection collection) {
 DBObject criteria = new BasicDBObject("type", "homework").append("student_id", 9);
 DBCursor cur = collection.find(criteria);
 try{
   while(cur.hasNext()){
   DBObject doc = cur.next();
   System.out.println(doc);
  }
 }finally{
  cur.close();
 }
}
public static void findWithCriteriaUsingQueryBuilder(DBCollection collection) {
 QueryBuilder builer =  QueryBuilder.start("type").is("homework").and("student_id").is(9).and("score").greaterThan(60);
 DBCursor cur = collection.find(builer.get(), new  BasicDBObject("student_id" , true).append("_id", false));
 try{
   while(cur.hasNext()){
   DBObject doc = cur.next();
   System.out.println(doc);
  }
 }finally{
  cur.close();
 }
}
}

Download the CODE from here.

Monday, June 24, 2013

Configure cURL for Windows 8

cURL

cURL is a computer software project providing a library and command-line tool for transferring data using various protocols. The cURL project produces two products, libcurl and cURL.

libcurl is a free client-side URL transfer library, supporting FTPFTPSGopherHTTPHTTPSSCPSFTPTFTPTelnetDICT, the file URI schemeLDAP, LDAPS, IMAPPOP3SMTP and RTSP. The library supports HTTPS certificates, HTTP POSTHTTP PUT, FTP uploading, Kerberos, HTTP form based upload, proxies, cookies, user-plus-password authentication, file transfer resume, and HTTP proxytunneling.

Since cURL uses libcurl, it supports a range of common Internet protocols, currently including HTTP, HTTPS, FTP, FTPS, SCP, SFTP, TFTP, LDAP, LDAPS, DICT, TELNET, FILE, IMAP, POP3, SMTP and RTSP (the last four only in versions newer than 7.20.0 or 9 February 2010).
The name of the project is a play on 'Client for URLs', originally with URL spelled in uppercase to make it obvious that it deals with URLs. The fact that it can also be pronounced 'see URL' also helped; it works as an abbreviation for "Client URL Request Library" or the recursive version: "Curl URL Request Library".

Requirements

Create folder in C:\ drive and named as CURL or any name that you want. Put the curl.exe , libssh2.dll and curl-ca-bundle.crt file in this folder curl.exe and  libssh2.dll files are download from cURL wizard. Open the Environment variable in windows and set the PATH of  directory in it. After this , Open the Command Prompt and Type.

c:\curl http://google.com


Download the full bundle from this Link and extract to the any drive and set the environment variables only.Enjoy with cURL.

Thursday, May 16, 2013

Search Noun , Adjectives & Verbs from Text Using JAVA with Apache OpenNLP Parse

Description : 

Some time we need to parse the text from text paragraph or we need to search some nouns , verbs etc from the paragraph. To sort the nouns and verbs or etc from paragraph , we need to implement Natural Language Processing , which is he part of Artificial Intelligence. But there are number of tools are provide to perform the task , and these tools are also used with programming languages. There are several tools are provide by the OpenNLP to process the paragraph , according to requirements , here is the documentation , that define how to use OpenNLP in different conditions or requirements. Today's we show how to use Apache OpenNLP to process the paragraph with the help of Java Using Parse Technique .

Requirements :

  • Download the Apache OpenNLP jars from OpenNLP website. 
  • Download JDK 7 (From my side , this is tested in JDK 7)
  • Download parser-chunking tool from here (there are so many tools are here)

Following is the code of Program : 

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;

import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;

public class ParserTest {

 static Set<String> nounPhrases = new HashSet<>();
 static Set<String> adjectivePhrases = new HashSet<>();
 static Set<String> verbPhrases = new HashSet<>();
 private static String line = "The Moon is a barren, rocky world     without air and water. It has dark lava plain on its surface. " +
"The Moon is filled wit craters. It has no light of its own. It gets its light from the Sun. The Moo keeps changing its " +
"shape as it moves round the Earth. It spins on its axis in 27.3 days stars were named after the Edwin Aldrin were the " +
first ones to set their foot on the Moon on 21 July 1969 They reached the Moon in their space craft named Apollo II";
 public void getNounPhrases(Parse p) {
  if (p.getType().equals("NN") || p.getType().equals("NNS") ||  p.getType().equals("NNP") || p.getType().equals("NNPS")) {
        nounPhrases.add(p.getCoveredText());
  }

  if (p.getType().equals("JJ") || p.getType().equals("JJR") || p.getType().equals("JJS")) {
    adjectivePhrases.add(p.getCoveredText());
  }
   
  if (p.getType().equals("VB") || p.getType().equals("VBP") || p.getType().equals("VBG")|| p.getType().equals("VBD") || p.getType().equals("VBN")) {
    verbPhrases.add(p.getCoveredText());
   }
   
  for (Parse child : p.getChildren()) {
        getNounPhrases(child);
  }
}
public void parserAction() throws Exception {
 InputStream is = new FileInputStream("en-parser-chunking.bin");
 ParserModel model = new ParserModel(is);
 Parser parser = ParserFactory.create(model);
 Parse topParses[] = ParserTool.parseLine(line, parser, 1);
 for (Parse p : topParses){
  //p.show();
  getNounPhrases(p);
 }
}

 public static void main(String[] args) throws Exception {
  new ParserTest().parserAction();
  System.out.println("List of Noun Parse : "+nounPhrases);
  System.out.println("List of Adjective Parse : "+adjectivePhrases);
  System.out.println("List of Verb Parse : "+verbPhrases);
 }
}

in this program the "NN","NNP" etc are the code for finding Nouns , Adjective , Verbs etc . Here are the list of all codes.
Download The Example Code From here

Monday, May 6, 2013

Convert large Images into thumbnails and maintain aspect ratio.

Description : 

Image scalar libraries are use to perform the action with images like to create images thumbnails and many more. there are different vendors provide different type of libraries to perform the action one is Google java API here  and other is scalar API here  for image scaling libraries and in this post define these libraries are easy to use and there is no need to implement large set of coding or mathematical computations . but if you want to customize something else or perform some action that are not present in this libraries so implement our own libraries . following describe "how to use and create image into thumbnails with image scalar libraries" .. 

Requirements:

  • Download and install JDK
  • Download the imgscalr-lib-4.2.jar or inject dependency
<dependencies>
 ...
 <dependency>
  <groupId>org.imgscalr</groupId>
  <artifactId>imgscalr-lib</artifactId>
  <version>4.2</version>
  <type>jar</type
  <scope>compile</scope>
 </dependency>
 ...
<dependencies>

Following is the example how to use : 

import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.ImageIO;

import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;

class ImageThumbnail{
     private void createThumbnail() throws FileNotFoundException,IOException{
          File file = new File("1.jpg");
          BufferedImage img = ImageIO.read(file);
          BufferedImage thumb = Scalr.resize(img, Scalr.Method.SPEED,102, 102, Scalr.OP_ANTIALIAS);
          ImageIO.write(thumb, "png", new File("thumb.png"));
     }

     public static void main(String[] args) throws FileNotFoundException,IOException{
          new ImageThumbnail().createThumbnail();
     }
}

Download the Source Code From this link


Thursday, April 25, 2013

Display tag library 1.2

Overview

The display tag library is an open source suite of custom tags that provide high-level web presentation patterns which will work in an MVC model. The library provides a significant amount of functionality while still being easy to use.

Requirements 

  • Download the display tag libraries from site . or use maven dependency
                             <dependency>
                         <groupId>displaytag</groupId> 
                         <artifactId>displaytag</artifactId> 
                         <version>1.1</version> 
                    </dependency>

  • In jsp file import taglib 
                  <%@taglib prefix="display" uri="http://displaytag.sf.net" %>

Note : Display tag internally use the 'TableTag.properties' file. If we really want to customize the display tag we need create the 'display.properties' file or add the properties in <display:set> tag in jsp . Put the 'display.properties' file in your class path . If you want to customize the css of table that generate by the <display> tag , create a css file and name the css file and create the class 'displayTable' and set the class attribute of <display> tag is 'displayTable' . 

The example of display tag as below : 

<display:table id="user" name="${users}" pagesize="2" class="displayTable "requestRI="listUsers.htm">
     <display:column property="userinfo.firstname" title="First Name" />
     <display:column property="userinfo.lastname" title="Last Name" />
     <display:column property="userName" title="Login" />
     <display:column title="Email" >
<a href="mailto:${user.userinfo.email}">${user.userinfo.email}</a>
     </display:column>
     <c:forEach var="roles" items="${roles}" >
<display:column title="${roles.name}">
  <c:forEach var="roleOfUser" items="${user.userRoles}">
    <c:set var="roleId" value="${roleOfUser.role}"></c:set>
<c:choose>
          <c:when test="${roleId.id eq roles.id }">
    <i class="icon-ok"></i>
  </c:when>
</c:choose>
  </c:forEach>
        </display:column>
     </c:forEach>
     <display:column title="Edit" > 
       <a href="#" onclick="javascript:window.location.href='editUser.htm?userName=${userList.userName}';">
  <i class="icon-pencil"></i>
       </a>
     </display:column>
     <display:column title="Delete">
        <a href="deleteUser.htm?id=${userList.userName}" onclick="return confirm('Warning: This deletes the data from everywhere! Are you sure?')">
  <i class="icon-remove"></i>
        </a>
     </display:column>
     <display:setProperty name="paging.banner.placement" value="bottom" />
     <display:setProperty name="basic.msg.empty_list"  value="No Records Found" />   </display:table>


Friday, April 12, 2013

Use Apache DBCP with Core Java


Apache DBCP : 

Many Apache projects support interaction with a relational database. Creating a new connection for each user can be time consuming (often requiring multiple seconds of clock time), in order to perform a database transaction that might take milliseconds. Opening a connection per user can be unfeasible in a publicly-hosted Internet application where the number of simultaneous users can be very large. Accordingly, developers often wish to share a "pool" of open connections between all of the application's current users. The number of users actually performing a request at any given time is usually a very small percentage of the total number of active users, and during request processing is the only time that a database connection is required. The application itself logs into the DBMS, and handles any user account issues internally.
There are several Database Connection Pools already available, both within Apache products and elsewhere. This Commons package provides an opportunity to coordinate the efforts required to create and maintain an efficient, feature-rich package under the ASF license.
The commons-dbcp package relies on code in the commons-pool package to provide the underlying object pool mechanisms that it utilizes.
DBCP now comes in two different versions, one to support JDBC 3 and one to support JDBC 4. Here is how it works:
  • DBCP 1.4 compiles and runs under JDK 1.6 only (JDBC 4)
  • DBCP 1.3 compiles and runs under JDK 1.4-1.5 only (JDBC 3)

Requirements : 

  • Download jars of DBCP commons-dbcp.jar and commons-pool.jar from here.
  • download Database dirver (in this example , we use MySQL so download mysql-connector-java-5.1.13-bin.jar) 

DbcpTest.java : 

import java.sql.Connection;
import java.sql.SQLException;

import javax.activation.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;

public class DbcpTest{
private static String connectURI = "jdbc:mysql://localhost/dbcp_test";
private static Connection conn;
private static ConnectionFactory connectionFactory;
private static ObjectPool connectionPool;
private static PoolingDataSource dataSource;
static {
try{
Class.forName("com.mysql.jdbc.Driver");
connectionFactory = new DriverManagerConnectionFactory(connectURI, "root","");
connectionPool = new GenericObjectPool<>();
new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false,true);
dataSource = new PoolingDataSource(connectionPool);
}catch(ClassNotFoundException ex){
System.out.println(ex.getMessage());
}
}
@Override
public void shutdownDatasource(DataSource ds) {
try{
BasicDataSource bds = (BasicDataSource) ds;
bds.close();
}catch(SQLException ex){
System.out.println(ex.getMessage());
}
}

@Override
public Connection getConnection() {
try{
conn = dataSource.getConnection();
if(conn != null){
return conn;
}else{
return null;
}
}catch(SQLException ex){
System.out.println(ex.getMessage());
return null;
}
}
}

When the code is compile ,with the help of getConnection() method , we get the Connection object and perform action .

Thursday, March 21, 2013

Insert and Retrieve Images from MySql Table Using Java

Demonstrate to insert and retrieve the images from database table. Mostly the images are stored from outside the database( some folders) and store the path of the images into database tables . but in some scenario we need to insert the images into database tables in binary format.

Requirements : 

  1. Download and Install JDK on your System.
  2. Download and Install MySql server and install.
  3. Download MySQL Connector or Drivers for use MySQL with Java.

Create Table in MySQL : 

CREATE TABLE `image` (
  `id` varchar(45) DEFAULT NULL,
  `size` int(11) DEFAULT NULL,
  `image` longblob
);

In MySQL when we use the blob type to store the data , it support only 5 kb image capacity. its depends on different database vendors . according to some more database vendors the blob type support large capacity. So the type of image type is depends on database vendors.

Insert The Image In Database : 

import java.sql.*;
import java.io.*;
public class InsertImagesMysql{
public static void main(String[] args){
System.out.println("Insert Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String userName = "root";
String password = "root";
Connection con = null;
try{
  Class.forName(driverName);
  con = DriverManager.getConnection(url+dbName,userName,password);
  Statement st = con.createStatement();
  File imgfile = new File("pic.jpg");
 
 FileInputStream fin = new FileInputStream(imgfile);
 
  PreparedStatement pre =
  con.prepareStatement("insert into Image values(?,?,?)");
 
  pre.setString(1,"test");
  pre.setInt(2,3);
  pre.setBinaryStream(3,(InputStream)fin,(int)imgfile.length());
  pre.executeUpdate();
  System.out.println("Successfully inserted the file into the database!");

  pre.close();
  con.close(); 
}catch (Exception e1){
System.out.println(e1.getMessage());
}
}
}

Compile & Run The Task : 

  1.  javac -cp mysql-connector-java-5.0.5-bin.jar;. InsertImagesMysql.java
  2.   java -cp mysql-connector-java-5.0.5-bin.jar;. InsertImagesMysql

Retrieve The Image From Database : 

import java.sql.*;
import java.io.*;
public class RetriveImagesMysql{
public static void main(String[] args){
System.out.println("Retrive Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String userName = "root";
String password = "root";
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select image from image");
int i = 0;
while (rs.next()) {
InputStream in = rs.getBinaryStream(1);
OutputStream f = new FileOutputStream(new File("test"+i+".jpg"));
i++;
int c = 0;
while ((c = in.read()) > -1) {
f.write(c);
}
f.close();
in.close();
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}

Compile & Run The Task : 


  1.  javac -cp mysql-connector-java-5.0.5-bin.jar;. RetriveImagesMysql.java
  2.   java -cp mysql-connector-java-5.0.5-bin.jar;. RetriveImagesMysql

Click Here To Download The Source Code



Thursday, February 28, 2013

Generate PDF using Jasper Reports and IReport

Jasper Reports :  JasperReports is an open source Java reporting tool that can write to a various types of report formats such as: PDF, HTML ,Microsoft Excel, RTF, ODT, Comma-separated values or XML files . It can be used in Java-enabled applications, including Java EE or web applications, to generate dynamic content. It reads its instructions from an XML or .jasper file

Ireport : iReport is a GUI tool that helps users and developers that use the JasperReports library to visually design reports.Through a rich and very simple to use GUI, iReport provides all the most important functions to create nice reports in little time. iReport can help people that don't know the JasperReports library create complex reports and learn the XML syntax, taking a look to the generated code. iReport can help skilled report designers compose very complex pages, saving a lot of time. iReport is written in Java.

Requirements : 

  1. Ireport Tool 4.5
  2. Apache Tomcat Container (up to 7.0)
  3. Libraries (jar files that needed to create the report from java)                                                                  Following the list of jar files : 
    • commons-beanutils-1.8.2.jar 
    • commons-collections-3.2.1.jar 
    • commons-digester-1.7.jar
    • commons-logging-1.1.jar 
    • groovy-all-1.7.5.jar 
    • iText-2.1.7.jar 
    • jasperreports-4.5.0.jar

Steps : 

Step 1 : Download and install the ireport tool from http://community.jaspersoft.com/download website .

Step 2 : Open the ireport tool and select the blank A4 template to create the report.


Step 3 : Design the report using ireport tools.

Step 4 : To connect the report with JavaBean Datasource , put the bean jar file in ireport class path Tools -> options -> classpath -> AddJar.


Step 5 : Save the report file at project/WEB-INF/ReportFormat/DemoReport.jrxml and put the project in Apache tomcat webapps directory.

Step 6 : create the jsp file to enter the user detail.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>PDF Generator</title>
</head>
<body>
            <h1>Generate PDF file using Jasper Reports </h1>
            <form action="addUser" method="post">
            <table>
                        <tr>
                                    <td><label for="firstName">First Name : </label></td>
                                    <td><input type="text" id="firstName" name="firstName"></td>
                        </tr>
                        <tr>
                                    <td><label for="lastName">Last Name : </label></td>
                                    <td><input type="text" id="lastName" name="lastName"></td>
                        </tr>
                        <tr>
                                    <td><label for="age">Age : </label></td>
                                    <td><input type="text" id="age" name="age"></td>
                        </tr>
                        <tr>
                                    <td><label for="sex">Sex : </label></td>
                                    <td>
                                                <select name="sex" id="sex">
                                                <option value="male">Male</option>
                                                <option value="female">Female</option>
                                                <option value="others">Others</option>
                                                </select>
                                    </td>
                        </tr>
                        <tr>
                                    <td><label for="address">Address : </label></td>
                                    <td><textarea name="address" id="address" rows="4" cols="20" ></textarea></td>
                        </tr>
                        <tr>
                                    <td><input type="submit" value="Report" name="submit"/></td>
                                    <td><input type="submit" value="Submit" name="submit"></td>
                        </tr>
            </table>
            </form>
</body>
</html>

Step 7 : Create the domain or Java Bean Class to add the detail of user.

package domain;
public class User {
                private String firstName;
                private String lastName;
                private String age;
                private String sex;
                private String address;
               
                /* public getter/setter */
}

Step 8 : Create the controller to add the list of users in List<User>.

package controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
…………………………….

@WebServlet("/jsp/addUser")
public class AddUser extends HttpServlet{
                public void doPost(HttpServletRequest request , HttpServletResponse response)
                                                throws IOException , ServletException{
                               
                                String submit = request.getParameter("submit");
                                if(submit.equalsIgnoreCase("submit")){
                                                createUser(request, response);
                                }else{
                                                processReports(request,response);
                                }
                }

private void createUser(HttpServletRequest request , HttpServletResponse response)
                                                throws IOException , ServletException{
                                String firstName = request.getParameter("firstName");
                                String lastName = request.getParameter("lastName");
                                String age = request.getParameter("age");
                                String sex = request.getParameter("sex");
                                String address = request.getParameter("address");
                               
                                User user = new User();
                                user.setFirstName(firstName);
                                user.setLastName(lastName);
                                user.setAge(age);
                                user.setSex(sex);
                                user.setAddress(address);
                               
                                UserCollections collections = new UserCollections();
                                collections.addUser(user);
                               
                                RequestDispatcher view = request.getRequestDispatcher("index.jsp");
                                view.forward(request, response);
                }
.........................................................................................................
}


package tempdatabase;


import java.util.ArrayList;
import java.util.List;

import domain.User;

public class UserCollections {
                private static List<User> userList = new ArrayList<User>();
               
                public void  addUser(User user) {
                                userList.add(user);
                }
               
                public List<User> getUserList() {
                                return userList;
                }
}

Step 9 : When the List<User> is filled with Users. Generate the pdf report report using following code.

package controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
…………………………….

@WebServlet("/jsp/addUser")
public class AddUser extends HttpServlet{
                public void doPost(HttpServletRequest request , HttpServletResponse response)
                                                throws IOException , ServletException{
                               
                                String submit = request.getParameter("submit");
                                if(submit.equalsIgnoreCase("submit")){
                                                createUser(request, response);
                                }else{
                                                processReports(request,response);
                                }
                }

private void processReports(HttpServletRequest request,
                                                HttpServletResponse response) {
                               
                                File filePath = new File(getServletContext().getRealPath("ReportFormat/DemoReport.jrxml"));
                                File savePath = new File(getServletContext().getRealPath("WEB-INF/GeneratedReports/userDetail.pdf"));
                                new ProcessReports().generateReport(filePath , savePath);
                                String path = savePath.toString();
                                try{
                                                if(path != null){
                                                                response.setContentType("application/pdf");
                                                                response.setHeader("content-dispostion","attachment;");
                                                                ServletContext ctx = getServletContext();
                                                                InputStream is = ctx.getResourceAsStream("WEB-INF/GeneratedReports/userDetail.pdf");
                                                               
                                                                int read = 0;
                                                                byte[] bytes = new byte[1024];
                                                               
                                                                OutputStream os = response.getOutputStream();
                                                                while((read = is.read(bytes)) != -1){
                                                                                os.write(bytes,0,read);
                                                                }
                                                                os.flush();
                                                                os.close();
                                                }
                                }catch(IOException ex){
                                                ex.printStackTrace();
                                }
                }

package tempdatabase;

import java.io.File;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class ProcessReports {
                public void generateReport(File filePath , File savePath) {
                                try{
                                                String pdfPath = savePath.toString();
                                                savePath.delete();
                                                JasperDesign design = JRXmlLoader.load(filePath);
                                                JasperReport report = JasperCompileManager.compileReport(design);
                                                JasperPrint print = JasperFillManager.fillReport(report, null,
                                                                                new JRBeanCollectionDataSource(new UserCollections().getUserList()));
                                                JasperExportManager.exportReportToPdfFile(print, pdfPath);
                                               
                                }catch(JRException ex){
                                                ex.printStackTrace();
                                }
                }
}

Step 10 : After generate the report , the pdf is open in browser.



To download the source code Click .