refermycode.com

Develop your world..

Create OSGI bundle from existing JAR

Hi Techies,

This blog will be helpful for devs who are working on some OSGI project in Java. OSGI framework is used to develop modular application and libraries. The deployable component of OSGI framework is know as “Bundle” which can be JAR or WAR. We can create separate bundle for each module of our application and we can easily add/remove this bundle without restarting the container. OSGI framework very flexible to manage dependencies between multiple bundles. There are many advantages of OSGI framework, you will get more information on their official website.

If you are working on project OSGI based project then you  will definitely need some 3rd party libraries to resolve dependencies of bundles. So many times you need to create some customized bundles from existing JAR/Libraries, hence this blog will help you to create OSGI bundle from existing JAR. I have used Eclipse IDE to demonstrate, how can we create OSGI bundle from existing JAR’s.

We need to follow the steps given below:

1. Create a New Plugin project by selection File-> New -> Project…-> Plug-in Development -> “Plug-in from Existing JAR Archives”

OSGI1

2. Add required jar files with the help of “Add External” option.

OSGI2

3. Fill the necessary information which is required for Bundle’s Manifest.mf file.

OSGI3

4. Select an OSGI framework as “Equinox” in Target Platform frame.

OSGI4

5. Uncheck the flag Unzip the JAR archive into the project.

OSGI5

Unchecking the checkbox Unzip the JAR archive into the project, prevents extracting class files from the Jar which is usually not necessary.

6. Press then finish. This will create a new project for you in selected workspace.

7. Now Remove the Java dependency from “Execution Environment”.

OSGI7

8. Open Manifest.mf and check the Exported packages which you want to make available for other bundles.

OSGI8

9. Now we are going to export this bundle from Export Functionality of Eclipse. Select your bundle and choose File -> Export -> Plug-in Development -> “Deployable plug-ins and fragment”.

OSGI9

10. Select the required bundles and Destination Directory.

OSGI10

In this way, we can create a OSGI bundle from existing JAR with the help of Eclipse.

Hope this blog will help you to understand to create your own OSGI bundles from existing JAR.
Please don’t forget to comment your feedback for this post. 🙂

Lambda Expression with Example

Hi Techies,

In previous blog, we have learned basic introduction of Lambda Expression. Now, we are going to learn few examples and some new APIs using Lambda Expression in detail. so before proceeding further, lets brush up some basic concepts of Lambda Expressions in something different way.

What is Lambda?

  • A Lambda is a function.
  • A function is computation that takes parameters and return value.
  • Until Java 8 function could be implemented by using methods.
  • A Lambda enables function to be passed around or stored like data.

Let us consider following example of sorting the list of Person objects with the name of person.

This is basic syntax to sort a list of object.

So in above example collections.sort() method requires parameter of type comparator, so we need to wrap compare method to one class which should need to implements comparator interface. But still we cannot call comparator class because sort method needs instance of comparator interface. so we are creating instance of comparePersonByName() class and passed to the sort method. So basically we are passing instance of comparator to the sort method.

This is sometimes becomes a problem because, The class that defines comparator sometime is far away from where it used. If our application have multiple files then it is difficult to figure out where actually comparator is located in our file system.

In order to deal with this problem, We can inline the compare() method inside an anonymous inner class. This avoids problem of declaring class into the somewhere else.

But there is lot of complexity here, both in the syntax and in fact we are creating a class and creating an instance of it, and just passing that instance to a function to sort method.

So let’s remove some syntax from this Collection.sort() method to simplify the structure of the code.

So now our syntax contains a method body which takes a 2 parameters Person p1 and Person p2 and perform some operation on it with compareTo() method and returning value to the Collection.sort() method.

So we can rewrite this into our first Lambda Expression, it just a function like,

So parameter are passed on the left side of an expression and list of parameters are enclosed with the parenthesis. The body of lambda expression are defined on the right side of special symbol -> (Arrow syntax) which is basically used to declare a Lambda Expression.

We can reduce the code Syntax as further,

Since we are sorting a list of Persons, the comparator function must be comparison of 2 Persons. The compiler knows this and hence it uses Type Inference to determine the types of parameters.We left off the type decoration making the Lambda Expression even more concise.

Note that, Java is still statically tie, means the type of p1 and p2 are still Person. They are determined at compile time. If compiler does not have information to infer what the type of p1 and p2 then it will generate the compile time error.

The sort method still calling compare() method, Even if we have not declared any compare method in the syntax of above mentioned Lambda expressions then How would you know that it is compare method?

Here is the answer,

Comparator is a special kind of interface called as functional interface. If you are declare a class which implements an interface then you need to provide implementation of each method declared in it. A Functional interface is an interface where you only have to implement a single method. In case of comparator it is the method called compare(). But since there is only a single method that you need to implement when you provide a Lambda Expression for it you don’t have need to provide the name, the Lambda Expression implicitly implements that single method inside the functional interface.

The all syntax which is used in the Lambda Expression we are already studies in the previous blog. If you want to know about the all syntax then please go through the previous blog.

Now we are going to learn why Functional Interfaces are important?

Anywhere functional interface is taken as argument you can write a Lambda Expression for it. Lets check out some other functional interfaces that already existed in Java 7, even though they wouldn’t called as functional interfaces previously.

A common example Is the Runnable interface. It defines a single method called run(). To create a new thread, you need to pass instance of Runnable interface to the Thread constructor. The tread will invoke the run method of Runnable interface. So below example will show how to create a thread using anonymous inner class.

so we can use the following Lambda Expression to perform the same operation which is mentioned in above example.

So in many cases the expression declared in anonymous inner class is replaced with Lambda expression.

New APIs using Functional Interfaces:

Oracle have added several new APIs in Java 8 that takes an functional interface and hence we can use Lambdas in it. For example let us consider the task to printing out each person in a list of Person.

Example 1:

We can use new forEach() loop to print out the list of Person with the help of Lambdas.

It might not seems very significant it look like we have just rearrange the syntax but this is an example of Internal iteration vs External iteration.

Lets us modify this list into the synchronized version of list, so that following example will make difference between Internal iteration and external iteration more clear.

so now this version list is a synchronised list which can be operated by multiple threads simultaneously.

The for loop which in body External iteration is implemented by using iterator. The for loop repetitively call the hasNext() and next() method of iterator (i.e. Two methods are concurrently working on the list). Since the list is synchronised list each method call on the iterator is synchronized, however another thread can modify the list between these calls if this occurs next method call on iterator results in concurrentModificationException. This example shows that the loop is been control from outside of list hence it is External iteration.

The forEach method on list illustrates Internal iteration. This is single method called on a list so list is synchronized for the entire duration of call and in such condition concurrent modification is not possible. Iteration of whole list Happens inside the single call hence it is Internal iteration.

Example 2:

Here is the another example in which we have to remove the all persons from list which having name equals to “ABC”. So we can find all such a type of person by using conventional for loop, but we can’t do the actual removal of that object. The reason is that we can only remove element by using remove() method of iterator but in for loop we do not have access to iterator that the for loop is using.

Instead of that, we need to write the for loop into long form, i.e. we have to explicitly get the iterator in advance using hasNext() and next() methods. Then we can call remove() method in appropriate place when we found person which match the criteria inside the loop.

In java 8, we can handle this situation by using new method removeIf() which removes each element from list where Lambda Expression returns the value as true.

Example 3:

Here is another example with new method which is used with Lambdas. Suppose we have to replace each element of list with uppercase equivalent. We can use same for loop which is use in the previous example with listIterator. Within the iterator we can use the set method listIterator to replace the new values with its uppercase in the same location.

So we can perform same operation with the help of Lambda Expression by using replaceAll() method.

Default Methods :

In Java 8, oracle has added new feature called as Default Methods, Default Methods has an implementation inside the interface, so for any class that has not provided implementation of this methods, the default implementation is used instead of that.

Default Methods are just like virtual methods, they can be overridden by subclasses. So following are the default methods which are added into the respective interface.

The list.sort() is replacement of Collection.sort() method,
Here is example of list.sort() method,

Above syntax can be replaced with,

Higher Order Functions :

Lets consider the following example which is used to sort the list with the help of comparator. In many cases same structure is used to sort the list with following manner,

Wouldn’t be nice if we can replicate that structure more easily?
So oracle introduce new method called Comparator.comparing(). this is higher order function, which is function that consumes or returns other functions.

In this case, comparing function takes function and gets right data from person object, this getter is called on each of the two Person objects and calls compareTo() on that values. The comparing function doesn’t do the comparison itself instead it construct the comparator function and returns it and this return is passed to list.sort() method.

Method References :

We have seen few lambda expression which are in the form of given an object, called method on that object and return the result. This form of lambda are so common, oracle has created a shorthand for it called as Method References. Using the new :: operator, we can mention a method by classname and methodname and it is equivalent to writing a Lambda Expression that takes an object if that type and calls the method on it.
Here we are rewritten the previous examples by using method references,

Two Level Sorting :

Let’s move to more complicated example of 2 level sorting. Suppose we want to sort the list with the age of Person and within the same group of age we have to sort the list by the name. So below is the code to sort the list using anonymous class,

In this example first compareTo() method is returning the result of ages while second compareTo() method is returning the result of comparing the names.

So it’s looking very complicated but if we break it down then we observe that it is combining the result of two comparators. Means if result is unequal then we are done and if result is equal then we call the second comparator and return its result.

We can use higher order functions to take two comparators and combine them into one.

So here the higher order function because it takes one function as parameter and returns value if that function to another function,

So firstly, we are sorting the list with the age with the help of first comparator which is invoked by comparing() method, if result of this comparator is equal then the result of this function is passing to another comparator which is sorting the list with the name with the help of new method thenComparing().

We can make this code more concise with static import,

So code readability is also increased by using the Lambda Expressions.

Old vs New :

Here is same code with the Lambda Expression,

here is the old and new code, side by side, Not only does old code have lot of inner class where embed it also embed some logic that isn’t very obvious. If you reading this code for first time then it can be hard to understand. By contrast the lambda based code makes it easy to create a very complicated structure by composition of small parts. Its pretty easy to create comparator using comparing() function. Its also pretty easy to combine comparator using the thenComparing() method. The resulting code is clear,concise and easy to modify.

Summary :

  • Lambdas are functions.
    A lambda can often replace an anonymous inner class.
  •  Java SE 8 defines new APIs using functional interfaces.
    Java 8 defines several new functional interfaces and new APIs that use them enabling them to be used with Lambdas.
  • Default Methods
    Default methods enable interfaces to view add compatibility.
  • Method References
    Method references are used for short hand Lambdas.
  • Higher Order Functions
    Higher Order Functions enables creation of more complex functions by composition of simple functions.

Lambdas make code read more like the problem statement. The resulting code is clear, concise and easy to maintain and modify.

Hope this blog will help you to understand some new APIs using Lambda Expression with Example in Java 8.
Please don’t forget to comment your feedback for this post. 🙂

References : Video of Stuart Marks – Oracle Corporation.
Image Courtesy : http://blog.takipi.com/compiling-lambda-expressions-scala-vs-java-8/

Lambda Expression in Java

Lambda Expression is way to passing a block of code to a method. To understand this concept we need to implement the functional interface and anonymous class which was used in the earlier version of the Java.

“Lambda Expression term is come from Mathematics, Greek letter Lambda basically associated with some kind of analogous situation where we are passing one function as a parameter to another function.”

package lambdaexpession;
interface Executable {
  void execute();
}

class Runner {
  public void run(Executable e) {
    System.out.println("Executing Code Block…");
    e.execute();
  }
}

public class App {
  public static void main(String args[]) {
    Runner runner = new Runner();
    runner.run(new Executable() {
      public void execute() {
        System.out.println("Anonymous Class Code Block.");
      }
    });
  }
}

The output of above code is

Executing Code Block…
Anonymous Class Code Block.

same thing we can implement with the help of Lambda Expression in following manner,
we need to replace above mentioned anonymous class code block

runner.run(new Executable() {
  public void execute() {
    System.out.println("Anonymous Class Code Block.");
  }
});

with following Lambda Expression,

runner.run( () -> System.out.println("Lambda Expression Code Block. "));

we get same output from Lambda Expression, i.e.

Executing Code Block…
Lambda Expression Code Block.

Hence by using Lambda Expression in Java, we are reducing code complexity and increasing the readability of our application.
Hope, you will get basic idea of Lambda Expression by above mentioned example. Below are some important points which will help you to clear understanding of Lambda Expressions in Java 8.

A) We can replace the Anonymous class with our Lambda Expression.
The below mentioned method

runner.run( () -> System.out.println("Lambda Expression Code Block."));

is replaced the whole anonymous class which is mentioned in above example. i.e.

runner.run(new Executable (){
  public void execute(){
    System.out.println("Anonymous Class Code Block.");
  }
});

where,

runner.run( () -> System.out. ("Lambda Expression Code Block."));

method name which is declared in Runner class.
List of Parameters required for Lambda Expression.
Code block which to be executed.

B) If we want to execute a multiple statements with the Lambda Expression then include the { and } parenthesis to code which you need to be executed. If you are adding multiple statements then it is mandatory to terminate the each statement with the “;”. If you are using { and } parenthesis and you have added single statement only then that single statement is also needs to be terminated with the help of “;”.

runner.run( () -> {
  System.out.println("Lambda Expression Code Block.");
  System.out.println("This is another Statement");
});
  • So, Lambda Expression of rows are associated with interface having single method in it.
  • With the help of Lambda Expression, we are simplifying the syntax for passing actual code to the another method/function.
  • In Java 8, if interface consist of single method in it, then it will refer as functional interface. hence “Interface having single method is called as Functional Interface”.
    exa. Comparable and Runnable interface.
  • C) If we want return value from block of code that is going to be execute,

    package lambdaexpession;

    interface Executable{
      int execute();
    }

    class Runner{
      public void run(Executable e){
        System.out.println("Executing Code Block…");
        int value = e.execute();
        System.out.println("Return value is : "+value);
      }
    }

    public class App{
      public static void main(String args[]){
        Runner runner = new Runner();
        runner.run(new Executable (){
          public int execute(){
            System.out.println("Anonymous Class Code Block.");
            return 7;
          }
        });
      }
    }

    output of above example is,

    Executing Code Block…
    Anonymous Class Code Block.
    Return value is : 7

    same thing we can implement with the help of Lambda Expression in following manner,

    runner.run( () -> {
      System.out.println("Lambda Expression Code Block.");
      return 8;
    });

    Hence, if we replace the above code in our example then we get following output after execution of program,

    Executing Code Block…
    Lambda Expression Code Block.
    Return value is : 8

    D) If we are returning only literal value from Lambda Expression then no need to mentioned the datatype of return value.

    runner.run( () -> 8 );

    E) If we want to pass parameter,

    package lambdaexpession;

    interface Executable {
      int execute(int a);
    }

    class Runner {
      public void run(Executable e) {
        System.out.println("Executing Code Block…");
        int value = e.execute(12);
        System.out.println("Return value is : " + value);
      }
    }

    public class App {
      public static void main(String args[]) {
        Runner runner = new Runner();
        runner.run(new Executable() {
          public int execute(int a) {
            System.out.println("Anonymous Class Code Block.");
            return 7 + a;
          }
        });
      }
    }

    For above mentioned program, we get following output,

    Executing Code Block…
    Anonymous Class Code Block.
    Return value is : 19

    same thing we can implement with the help of Lambda Expression in following manner,

    runner.run( (int a) -> {
      System.out.println("Lambda Expression Code Block.");
      return 7+a;
    });

    we will get following output if we replace anonymous class with our Lambda Expression,

    Executing Code Block…
    Lambda Expression Code Block.
    Return value is : 19

    F) If we are using Lambda Expression then there is no need to define parameter type. Our Compiler will autodetect the type of parameter from the declaration of method from calling class.

    runner.run( (a) -> {
      System.out.println("Lambda Expression Code Block.");
      return 7+a;
    });

    G) In case of method overloading, we need to specify the datatype of parameters to avoid the ambiguity between overloading methods.

    package lambdaexpession;

    interface Executable{
      int execute(int a);
    }

    interface StringExecutable{
      int execute(String a);
    }

    class Runner{
      public void run(Executable e){
        System.out.println("Executing Code Block…");
        int value = e.execute(12);
        System.out.println("Return value is : "+value);
      }
     
      public void run(StringExecutable e){
        System.out.println("Executing Code Block…");
        int value = e.execute("Hello");
        System.out.println("Return value is : "+value);
      }
    }

    public class App{
      public static void main(String args[]){
        Runner runner = new Runner();
        runner.run(new Executable (){
          public int execute(int a){
            System.out.println("Anonymous Class Code Block.");
            return 7 + a;
          }
        });
      }
    }

    so after execution of this code, we will get following output,

    Executing Code Block…
    Anonymous Class Code Block.
    Return value is : 19

    same thing we can implement with the help of Lambda Expression in following manner,

    runner.run( (int a) -> {
      System.out.println("Lambda Expression Code Block.");
      return 7+a;
    });

    so after replacing and executing of our Lambda Expression, we will get following output,

    Executing Code Block…
    Lambda Expression Code Block.
    Return value is : 19

    H) If we have single parameter then no need to define the datatype of parameter as well as no need to add parenthesis for parameters.

    runner.run( a -> {
      System.out.println("Lambda Expression Code Block.");
      return 7+a;
    });

    I) If we want to pass multiple parameters then we need to add parenthesis compulsory.

    runner.run( (a,b) -> {
      System.out.println("Lambda Expression Code Block.");
      return a+b;
    });

    J) If we want to access the variable from main (parent) method in the block of Lambda Expression.

  • If we want to access variable from calling method in the anonymous class then it should be final for previous version of Java. But in Java 8, it is not mandatory to declare that variable as final.
  • But if we are re-assigning the value of that variable then compiler will throw Compile time Exception.
  • Means if we are not re-assigning value to variable in calling method then it is treated like final variable but it is not actually final variable, we can called it as effectively final variable.
  • public class App{
      public static void main(String args[]){
        int c = 100;
        // c=8; mustn’t do this.
        Runner runner = new Runner();
        runner.run(new Executable (){
          public int execute(int a, int b){
            System.out.println("Anonymous Class Code Block.");
            return a+b+c;
          }
        });
      }
    }

    same thing we can implement with the help of Lambda Expression in following manner,

    runner.run( ( a,b ) -> {
      System.out.println("Lambda Expression Code Block.");
      return a+b+c;
    });

    K) Lambda Expression doesn’t have their own scope, so we can access variable from calling method, while in previous version of Java, anonymous class having their own scopes, so you can re-declare the variable with same declaration as declared in the parent method.
    This variable in the anonymous class is treated as new variable.

    public class App{
      public static void main(String args[]){
        int d = 77;
        Runner runner = new Runner();
        runner.run(new Executable (){
          public int execute(int a, int b){
            System.out.println("Lambda Expression Code Block.");
            //int d=8; can do this in anonymous classes.
            return a+b+c;
          }
        });
      }
    }

    same thing we can implement with the help of Lambda Expression in following manner,

    runner.run( ( a,b ) -> {
      System.out.println("Lambda Expression Code Block.");
      //int d=5; we can’t do this as this is no new scope.
      return a+b+c;
    });

    L) We can store all the Lambda Expression into equivalent object also.

    Executable ex = (a,b) -> {
      System.out.println("Lambda Expression Code Block.");
      return a+b;
    }
    runner.run(ex);

    M) We can assign the Lambda Expression to superclass of interface, for that we need to typecast that object to superclass object type.

    Object codeBlock = (Executable) (a,b) -> {
      System.out.println("Lambda Expression Code Block.");
      return a+b;
    }

    This is very useful to implement comparable interface.

    So this is some basic and simple Lambda Expressions which is used in Java 8. We will see some real time examples of Lambda Expressions in our Next Post.

    Hope this blog will help you to understand the basic concept of Lambda Expressions in Java 8.
    Please don’t forget to comment your feedback for this post. 🙂

    References : Video of Cave of Programming.

    Need of Collections framework in Java

    In this tutorial, we will going to discuss about the Need of Collections framework in Java. As we have alternate ways to store the data in Java then why we should use the Collection framework?

    To answer this question, let us study the some points which is given below:

    In traditional way, if we required multiple variables in our java program to store the data then we can use multiple variable by declaring it with its datatypes but in this scenario if numbers of variables are increased then it will decrease the readability of our program due to declaration of multiple variable in our program.

    To overcome this problem, later we can use arrays, to store the multiple values in single variable. But using array include several problems which is explained below,

    1. When we want to use array in our program, we need to define the size of array in declaration of array. This will restrict the user to add element with limited size of array, means We can not add element greater than the size which is mentioned while declaration of array. If user still trying to add element to array then it will gives the array out of bound exception.

    Collection1

    1. If user declared an array with maximum number of elements and at execution time if our program use lesser numbers of element then it will cause the wastage of memory. Hence we can not shrink or grow the size of an array dynamically, we should need to know exact size of an array in advance.
    1. We can insert the element with the same type (homogeneous datatype) which we have declared while array declaration, means we can not add element with heterogeneous datatype. If we will going to add element with heterogeneous datatype then this will throws incompatible type execution while compilation of java program.

    Collection2

    1. There is no any predefined method are available for array due to that, we have to write our own logic to perform some basic operation like searching and sorting.

    To overcome above mentioned problems, we need to use Collections in our programming language.

    Advantage of Collections:

    1. Collections can be Growable in nature, means we can add or remove elements without defining predefined fixed size.
    2. Collections can hold heterogeneous elements as well as homogeneous elements, we can study this chapter in generous chapter.
    3. Collections are based on some data structure which provides some predefined method to perform basic operation like searching and sorting.

    Difference between Array and Collections :

    ArrayCollections
    1. Arrays are Fixed in size we can not add element dynamically.1. Collection are Growable in nature, we can add elements dynamically.
    2. With respect to memory array are not recommended to use.2. With respect to memory Collections are recommended to use.
    3. With respect to performance array are recommended to use.3. With respect to performance Collections are not recommended to use.
    4. In Array we can insert only Homogeneous data.4. In Collections we can insert Heterogeneous as well as Homogeneous data also.
    5. Underlying data structure not available hence readymade methods are not available.5. Every Collection is based on some data structure.
    6. We can insert primitive elements as well as object.6. We can insert only objects but not primitive elements.

    Export the multisheet excel file by using Jasper.

    In this blog we are going to learn, how to export multisheet excel file by using Jasper. So we will take an example in which we will print some information in one sheet and some information in another sheet.

    Employee NumberEmployee NameEmployee AddressEmployee Salary
    1001Adams Springfield 40,000
    1002Anderson Clinton 50,000
    1003Clark Madison 50,000
    1004David Washington 60,000
    1005Harris Clinton 50,000
    1006Johnson Franklin 60,000
    1007Mitchell Washington 50,000
    1008Nelson Chester 30,000
    1009Robinson Marion 60,000
    1010Roberts Greenville 70,000
    1011Smith Georgetown 80,000
    1012Scott Salem 40,000

    In another sheet we will display the information of Department.

    Department NumberDepartment NameLocation
    101HR Madison
    102IT Madison
    103Payroll Madison
    104Inventory Washington
    105Production Washington

    We have print this records into 2 different sheets of single excel file.

    So let us start with the designing phase,

    In iReport we are going to create 2 different design (Sub Reports) for both sheets, one for Employee Information and another for Department Information. Hence we are merging these 2 Sub Report into another report which we are calling here Main Report.

    Step 1: Design of First Sub Report.

    We need to add the fields which is required to display the information about Employees. Hence we are going to add the necessary field into the Column Header and Detail section as shown in following screenshot.

    Blog4_1

    Here is the sample code of First Subreport.

    <?xml version="1.0" encoding="UTF-8"?>
    <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="mayursreport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <property name="ireport.zoom" value="1.464100000000001"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <field name="employeeNumber" class="java.lang.String"/>
    <field name="employeeName" class="java.lang.String"/>
    <field name="employeeAddress" class="java.lang.String"/>
    <field name="employeeSalary" class="java.lang.String"/>
    <pageHeader>
    <band height="50">
    <staticText>
            <reportElement x="120" y="16" width="300" height="20"/>
            <textElement textAlignment="Center">
                    <font size="12" isBold="true"/>
            </textElement>
            <text><![CDATA[This is First SubReport Title!]]></text>
    </staticText>
    </band>
    </pageHeader>
    <columnHeader>
    <band height="30">
    <staticText>
            <reportElement x="17" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Number]]></text>
    </staticText>
    <staticText>
            <reportElement x="150" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Name]]></text>
    </staticText>
    <staticText>
            <reportElement x="283" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Address]]></text>
    </staticText>
    <staticText>
            <reportElement x="420" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Salary]]></text>
    </staticText>
    </band>
    </columnHeader>
    <detail>
    <band height="26">
    <textField>
            <reportElement x="17" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{employeeNumber}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="150" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{employeeName}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="283" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{employeeAddress}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="420" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{employeeSalary}]]></textFieldExpression>
    </textField>
    </band>
    </detail>
    </jasperReport>

    Step 2: Design of Second Sub Report.

    In this step we will add the fields which is required to display the information about Department. Hence we are going to add the necessary field into the Column Header and Detail section as shown in following screenshot.

    Blog4_2

    Here is the sample code of Second Subreport.

    <?xml version="1.0" encoding="UTF-8"?>
    <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="mayursreport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <property name="ireport.zoom" value="1.464100000000001"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <field name="departmentNumber" class="java.lang.String"/>
    <field name="departmentName" class="java.lang.String"/>
    <field name="departmentLocation" class="java.lang.String"/>
    <pageHeader>
    <band height="50">
    <staticText>
            <reportElement x="114" y="20" width="300" height="20"/>
            <textElement textAlignment="Center">
                    <font size="12" isBold="true"/>
            </textElement>
            <text><![CDATA[This is Second SubReport Title!]]></text>
    </staticText>
    </band>
    </pageHeader>
    <columnHeader>
    <band height="30">
    <staticText>
            <reportElement x="17" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Department Number]]></text>
    </staticText>
    <staticText>
            <reportElement x="150" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Department Name]]></text>
    </staticText>
    <staticText>
            <reportElement x="283" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Location]]></text>
    </staticText>
    </band>
    </columnHeader>
    <detail>
    <band height="26">
    <textField>
            <reportElement x="17" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{departmentNumber}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="150" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{departmentName}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="283" y="5" width="120" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{departmentLocation}]]></textFieldExpression>
    </textField>
    </band>
    </detail>
    </jasperReport>

    Step 3: Design of Main Report.

    In this step we are going to add this two subreports into our main report. To Separate these two reports we are going to use page break tool which is provided by iReport tool. So add first subreport in fist detail band, then page break in second detail band and finally second subreport in third detail band as shown in following screenshot.

    Blog4_3

    Here is the sample code of Main Report.

    <?xml version="1.0" encoding="UTF-8"?>
    <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="mayursreport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <parameter name="SUBREPORT_1" class="net.sf.jasperreports.engine.JasperReport"/>
    <parameter name="SUBREPORT_2" class="net.sf.jasperreports.engine.JasperReport"/>
    <parameter name="SUBREPORT_DATA_1" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <parameter name="SUBREPORT_DATA_2" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
    <detail>
    <band height="26">
    <subreport>
            <reportElement mode="Transparent" x="0" y="0" width="555" height="26"/>
            <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource ($P{SUBREPORT_DATA_1}.getData())]]></dataSourceExpression>
            <subreportExpression class="net.sf.jasperreports.engine.JasperReport"><![CDATA[$P{SUBREPORT_1}]]></subreportExpression>
    </subreport>
    </band>
    <band height="13">
    <break>
            <reportElement mode="Opaque" x="0" y="6" width="555" height="1"/>
    </break>
    </band>
    <band height="27">
    <subreport>
            <reportElement mode="Transparent" x="0" y="0" width="555" height="26"/>
            <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource ($P{SUBREPORT_DATA_2}.getData())]]></dataSourceExpression>
            <subreportExpression class="net.sf.jasperreports.engine.JasperReport"><![CDATA[$P{SUBREPORT_2}]]></subreportExpression>
    </subreport>
    </band>
    </detail>
    </jasperReport>

    In this way, we have finished design phase, now let us move to the Java Code.

    We need to create two separate POJO classes to store the information for Employee and Department, hence we have created distinct classes for Employee and Department in same package.

    Here is sample code for Employee class.

    package com.refermycode.mypackage;
    /*
    * @author Mayur
    */

    public class Employee {
    String employeeNumber = "";
    String employeeName = "";
    String employeeAddress = "";
    String employeeSalary = "";
    public String getEmployeeAddress() {
    return employeeAddress;
    }
    public void setEmployeeAddress(String employeeAddress) {
    this.employeeAddress = employeeAddress;
    }
    public String getEmployeeName() {
    return employeeName;
    }
    public void setEmployeeName(String employeeName) {
    this.employeeName = employeeName;
    }
    public String getEmployeeNumber() {
    return employeeNumber;
    }
    public void setEmployeeNumber(String employeeNumber) {
    this.employeeNumber = employeeNumber;
    }
    public String getEmployeeSalary() {
    return employeeSalary;
    }
    public void setEmployeeSalary(String employeeSalary) {
    this.employeeSalary = employeeSalary;
    }
    }

    Here is sample code for Department.

    package com.refermycode.mypackage;

    /*
    * @author Maddy
    */

    public class Department {
    String departmentNumber = "";
    String departmentName = "";
    String departmentLocation = "";
    public String getDepartmentNumber() {
    return departmentNumber;
    }
    public void setDepartmentNumber(String departmentNumber) {
    this.departmentNumber = departmentNumber;
    }
    public String getDepartmentName() {
    return departmentName;
    }
    public void setDepartmentName(String departmentName) {
    this.departmentName = departmentName;
    }
    public String getDepartmentLocation() {
    return departmentLocation;
    }
    public void setDepartmentLocation(String departmentLocation) {
    this.departmentLocation = departmentLocation;
    }
    }

    Now let us write a another class which we will use to store the data and export it into the Excel file.

    Here is sample code for JasperBlog4.java which include the main method in it.

    package com.refermycode.mypackage;

    import java.io.*;
    import java.util.AbstractList;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import net.sf.jasperreports.engine.*;
    import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
    import net.sf.jasperreports.engine.design.JasperDesign;
    import net.sf.jasperreports.engine.export.JRXlsExporter;
    import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
    import net.sf.jasperreports.engine.xml.JRXmlLoader;

    /*
    * @author Mayur
    */

    public class JasperBlog4 {

    /* Method to add Employee Information */
    public static List addEmployeeInfo() {
    List employeeList = new ArrayList();

    Employee employee = new Employee();
    employee.setEmployeeNumber("1001");
    employee.setEmployeeName("Adams");
    employee.setEmployeeAddress("Springfield");
    employee.setEmployeeSalary("40,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1002");
    employee.setEmployeeName("Anderson");
    employee.setEmployeeAddress("Clinton");
    employee.setEmployeeSalary("50,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1004");
    employee.setEmployeeName("Clark");
    employee.setEmployeeAddress("Madison");
    employee.setEmployeeSalary("50,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1004");
    employee.setEmployeeName("David");
    employee.setEmployeeAddress("Washington");
    employee.setEmployeeSalary("60,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1005");
    employee.setEmployeeName("Harris");
    employee.setEmployeeAddress("Clinton");
    employee.setEmployeeSalary("50,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1006");
    employee.setEmployeeName("Johnson");
    employee.setEmployeeAddress("Franklin");
    employee.setEmployeeSalary("60,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1007");
    employee.setEmployeeName("Mitchell");
    employee.setEmployeeAddress("Washington");
    employee.setEmployeeSalary("50,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1008");
    employee.setEmployeeName("Nelson");
    employee.setEmployeeAddress("Chester");
    employee.setEmployeeSalary("30,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1009");
    employee.setEmployeeName("Robinson");
    employee.setEmployeeAddress("Marion");
    employee.setEmployeeSalary("60,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1010");
    employee.setEmployeeName("Roberts");
    employee.setEmployeeAddress("Greenville");
    employee.setEmployeeSalary("70,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1011");
    employee.setEmployeeName("Smith");
    employee.setEmployeeAddress("Georgetown");
    employee.setEmployeeSalary("80,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1012");
    employee.setEmployeeName("Scott");
    employee.setEmployeeAddress("Salem");
    employee.setEmployeeSalary("40,000");
    employeeList.add(employee);

    return employeeList;
    }

    /* Method to add Department Information */
    public static List addDepartmentInfo() {
    List departmentList = new ArrayList();

    Department department = new Department();
    department.setDepartmentNumber("101");
    department.setDepartmentName("HR");
    department.setDepartmentLocation("Madison");
    departmentList.add(department);

    department = new Department();
    department.setDepartmentNumber("102");
    department.setDepartmentName("IT");
    department.setDepartmentLocation("Madison");
    departmentList.add(department);

    department = new Department();
    department.setDepartmentNumber("103");
    department.setDepartmentName("Payroll");
    department.setDepartmentLocation("Madison");
    departmentList.add(department);

    department = new Department();
    department.setDepartmentNumber("104");
    department.setDepartmentName("Inventory");
    department.setDepartmentLocation("Washington");
    departmentList.add(department);

    department = new Department();
    department.setDepartmentNumber("105");
    department.setDepartmentName("Production");
    department.setDepartmentLocation("Washington");
    departmentList.add(department);

    return departmentList;
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {
    try {
    /* Hashmap to store all Parameters required for Export Operation */
    HashMap parameters = new HashMap();

    /* Loading and Compiling First Subreport */
    InputStream inputStreamSubReport1 = new FileInputStream("C:/JasperBlog4/src/com/refermycode/mypackage/SubReport1.jrxml");
    JasperDesign jasperDesignSubReport1 = JRXmlLoader.load(inputStreamSubReport1);
    JasperReport jasperReportSubReport1 = JasperCompileManager.compileReport(jasperDesignSubReport1);

    /* Loading and Compiling Second Subreport */
    InputStream inputStreamSubReport2 = new FileInputStream("C:/JasperBlog4/src/com/refermycode/mypackage/SubReport2.jrxml");
    JasperDesign jasperDesignSubReport2 = JRXmlLoader.load(inputStreamSubReport2);
    JasperReport jasperReportSubReport2 = JasperCompileManager.compileReport(jasperDesignSubReport2);

    /* Loading and Compiling Main Report */
    InputStream inputStream = new FileInputStream("C:/JasperBlog4/src/com/refermycode/mypackage/MainReport.jrxml");
    JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

    List employeeList = addEmployeeInfo();
    List departmentList = addDepartmentInfo();

    /* Putting the Subreport and Data into Parameters */
    parameters.put("SUBREPORT_1", jasperReportSubReport1);
    parameters.put("SUBREPORT_2", jasperReportSubReport2);
    parameters.put("SUBREPORT_DATA_1", new JRBeanCollectionDataSource(employeeList));
    parameters.put("SUBREPORT_DATA_2", new JRBeanCollectionDataSource(departmentList));

    /* Putting some Dummy Data for Main Report,
    * if you not pass this dummy data then result will be blank sheet.
    * and if you send multiple times then it will print same data multiple times.*/

    ArrayList mainReportsList = new ArrayList&lt;&gt;();
    mainReportsList.add("DummyValue");

    JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(mainReportsList);
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);

    /*If you want to print the data in PDF format then you can add this line into code.
    JasperExportManager.exportReportToPdfFile(jasperPrint, "C:/test_jasper.pdf");
    */

    ByteArrayOutputStream outputByteArray = new ByteArrayOutputStream();
    OutputStream outputfile = new FileOutputStream(new File("C:/test_jasper.xls"));

    JRXlsExporter xlsExporter = new JRXlsExporter();
    xlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
    xlsExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, outputByteArray);

    /* This is Properties of Excel file which is used for configuration setting. */
    xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
    xlsExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
    xlsExporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.FALSE);
    xlsExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);

    xlsExporter.exportReport();
    outputfile.write(outputByteArray.toByteArray());

    } catch (JRException ex) {
    Logger.getLogger(JasperBlog4.class.getName()).log(Level.SEVERE, null, ex);
    }
    }
    }

    To export this file we need additional library called as poi-X.X.jar  which can be found in following path of installation folder of iReport.

    “iReport-X.X.X\ireport\modules\ext”.

    Include this into classpath of project. If you forget to include this library in Project then it will throw following exception while execution of Project.

    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/RichTextString

    If you have follow all the above steps then run your project and you will get following excel sheet with two sheets as shown in following screenshot.

    Blog4_4

    In short when we need to display our data on multiple sheets then we need to add below 2 things into ireport design.

    1. Page Break Component to create multiple pages.
    2. Set following property “net.sf.jasperreports.export.xls.one.page.per.sheet” to TRUE.

    In this way we can export the multisheet excel file by using Jasper.

    Please don’t forget to comment your feedback for this post. 🙂

    Add new font in Jasper Reports Font Library.

    In this blog we are going to add new font in Jasper Font Library to remove font dependency. Hope you have read my previous blog on Remove font dependency from Jasper Report Font Library. As discussed in previous blog if we are using any font which is not present in our Jasper Report Font Library then it will raised following exception while export phase,

    net.sf.jasperreports.engine.util.JRFontNotFoundException:
    Font ‘Font_Name’ is not available to the JVM.

    we can also resolve above exception by adding the font which is missing in our Jasperreports-font.X.X.X.jar Library. So let us have look on this method in detail.

    Method 2 : by adding missing font property.
    To add missing fonts into the library we can create our own custom library for Jasperreports-font.X.X.X.jar. So follow below given steps to create your custom font library for Jasper Report Font with the help of iReport.

    Step 1:
    To install missing fonts in iReport go to ” Tools >> Options >> Fonts >> Install Font ” as shown in following screenshot.

    Blog2_2

    Step 2:
    Add your fonts ttf file from browse button and click on Next button as shown in following screenshot.

    Blog2_3

    Step 3:
    After adding fonts ttf file, you need to add family details by adding Bold, Italic and Bold-Italic version of font. If you have not added these version of fonts then it will not change the font style even if we add in our report design. Click on next button after adding the font family version ttf files as shown in following screenshot.

    Blog2_4

    Step 4:
    In this step select the locale for your region, In this example I have added English(India) as shown in following screenshot.

    Blog2_5

    Step 5:
    After that you can also manage the font mapping for avoiding the missing font property in OS.
    as it is not mandatory you can skip this and click on finish button as shown in following screenshot.

    Blog2_6

    Step 6:
    You can add multiple fonts by repeating step 2 to 5. After adding all required fonts click on Export as Extension button and save the the library with .jar Extension. as shown in following screenshot.

    Blog2_7

    Step 7:
    After following all above steps you will get the your custom library with all your fonts.

    Blog2_8

    Now you can use this jar for Jasperreports-font.X.X.X.jar which will be present in your project library or classpath. After replacing this library you will get the your desire output with proper fonts.

    Hope this blog will help you to add new font in Jasper Font Library to remove font dependency.

    Please don’t forget to comment your feedback for this post 🙂

    Remove font dependency in Jasper Report.

    In this blog we are going to learn cool stuff which will help us to Remove font dependency in Jasper Report Font Library. So let us see how we can remove the font dependency from Jasper Report Java Application. First of all let us see why we are going to remove the font dependency from Jasper.
    So Answer is here,

    Jasper Report requires 2 libraries for generating any report,
    1. Jasperreport.X.X.X.jar
    2. Jasperreports-font.X.X.X.jar

    when we are create any Jasper Report application then it requires some fonts for writing data in export phase, so it will take the font from Jasperreports-font.X.X.X.jar library. Generally Jasperreports-font.X.X.X.jar library has some default fonts shown in below screenshot.

    Blog2_1

    There are following default fonts in Jasper Report library

    • DejaVu Sans
    • DejaVe Sans Mono
    • DejaVu Serif
    • Monospaced
    • SansSerif
    • Serif

    For each above font there are 4 different font’s .ttf files are present for font faces which are used for Normal, Bold, Italic and Bold-Italic style. If we have used any font which is not present in our Jasperreports-font.X.X.X.jar library then it will throw an exception something like

    net.sf.jasperreports.engine.util.JRFontNotFoundException:
    Font ‘Font_Name’ is not available to the JVM.

    This exception occurs due to unavailability of font in Jasper report font library. We can not move further until and unless resolve this exception, So now we will learn how to avoid such types of exception while playing with Jasper Report and different types of Fonts.

    There are two method to avoid such a problem.
    Method 1 : by setting ignore missing font property and default font property.
    Method 2 : by adding missing font property.
    We will see Method 2 into next blog. For Now Let us focus on Method 1 in detail.

    In this method we can avoid above exception by ignoring the missing font property and using default font instead of missing font from our Jasperreports-font.X.X.X.jar library. In Jasper Report library all properties are already defined in default.jasperreports.properties file. There is one property present “net.sf.jasperreports.awt.ignore.missing.font” which help us to remove font dependency from Jasper Report design but it is by default set to “false”. If we try to export with this setting and at the time of filling data in report, Jasper Report fill manager fails to find the mentioned font in Jasper Report design then it will throws an exception which is mentioned earlier in this blog.
    So we can avoid missing font exception by setting following property in Java Code.

    JRProperties.setProperty("net.sf.jasperreports.awt.ignore.missing.font", "true");

    or we can set this property by entering following line into .jrxml file.

    <property name="net.sf.jasperreports.awt.ignore.missing.font" value="true"/>

    By using above code we can remove font dependency but for exporting report Jasper Needs default font which will use instead of missing fonts. Default Font property is also predefined into default.jasperreports.properties file with the property “net.sf.jasperreports.default.font.name”. We can use the default font in place of our missing font which is mentioned in Jasper Report library. The value of default font is set to “SansSerif”, If we want any other font for it then we can change it manually.

    For setting any default font name, we can set following property in Java Code.

    JRProperties.setProperty("net.sf.jasperreports.default.font.name", "Default_Font_Name");

    or we can set this property by entering following line into .jrxml file.

    <property name="net.sf.jasperreports.default.font.name" value="Default_Font_Name"/>

    In this way we can add above properties into our application which help us to remove the font dependency from Jasper Report. In next blog we will see the how to add our fonts in Jasper Report Font Library.

    Hope this blog will help you to remove font dependency in Jasper Report Font Library.

    Please don’t forget to comment your feedback for this post 🙂

    How to add alphabetical sequence in Jasper Report.

    In this blog we are going to learn one interesting topic of Jasper Report technology. We are going to generate and add alphabetical sequence in Jasper Report. So first of all, let us create simple report which includes the numeric sequence for records. Create a simple PDF report with the help of following steps in Java and Jasper.

    We are going to create a report which will print the following information of Employees in our PDF.

    Serial NumberEmployee NumberEmployee NameEmployee AddressEmployee Salary
    11001AjitLatur40,000
    21002AmitAurangabad50,000
    31003AniketNashik50,000
    41004AnupPune60,000
    51005HiteshAkurdi40,000
    61006KuldeepHyderabad60,000
    71007MayurVishrantwadi50,000
    81008OmkarRajgurunagar30,000
    91009TusharKopargaon60,000
    101010VijayShirdo50,000

    So, we will start with the Design part first,

    Step 1:
    Create a new report in Jasper with blank A4 template. If you are new in Jasper Report then you can refer our tutorial of Jasper from here. Jasper Tutorial includes the information of all the necessary environment setup and provide the guidance for creating a simple report in Jasper and Java.

    So now we directly jump to design phase in iReport. Here we are going to design report in Java language hence change the language of report to Java. To change the language click on report in Report Inspector Window and find the language property in Properties window of iReport, by default it is set to Groovy language, click on combo box and change it to Java, as show in following screenshot.

    chapter5_0

    Step 2:

    We are going to display the information of Employees which is filled in above table, we are going to use Field component of Jasper which are the placeholder and it will stored the values which we want to display in our report. These value will be set with the help of Java POJO classes which we will see in the later part in this blog.
    For adding the field go into the Report Inspector Window of iReport and click Right Button of mouse on Field and select the “Add Field” option to add the field in report as shown following screenshot.

    chapter5_1

    Step 3:

    After that select added field and rename it by selecting rename option. Jasper provide multiple datatypes for field, parameters and variables. You can change the datatype of Field from property window of iReport. In this chapter we are going to use string datatype to generate the report and String is Default datatype for any field, variable or parameter, hence I am not going to change the datatype. If you want different datatype then you can select the field and change the datatype which you want in your report as shown in following screenshot.

    chapter5_2

    Step 4:

    In this chapter we are just putting the values which is set from Java side so we will remove the other band except Detail and Column Header Band. So drag and drop the required fields in Detail Band. When you add the fields in the Detail Band, we get an option to which value should be display in the field section, mean value which is stored by field or you can show count of the selected field as shown in following screenshot.

    chapter5_3

    Step 5:

    When you used drag and drop method for adding the field in Detail Band of report then Static Text is automatically gets added in the Column Header of report with the label name as Default text in it.

    chapter5_4

    Step 6:

    We can change it by double click in the static text. so we will change the Header labels to standardise our report with proper Header names, After changing the the labels our report design will looks as shown in following screenshot.

    chapter5_5

    Step 7:

    Now lets move to the actual part on our blog. We have to add Sequence Number in our Report. We can also manage the sequence by adding one extra field for sequence number and set value of it from Java. But in case of grouping it will not works properly. Because when we use the grouping concept then Jasper have ability to group the records on the basis of field which is used for grouping and these grouping can be break our sequence if we not handled it from Java. So we will handle these sequence in Jasper instead of Java by using some build in Variable provided by Jasper.

    Hence as shown in below screenshot, we are going to use the build in variable REPORT_COUNT to generate the sequence number for each record of our report.

    Blog1_1

    Now, we can see the generated sample XML code (.jrxml) in XML view of iReport. Our jrxml file is

    <?xml version="1.0" encoding="UTF-8"?>
    <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report2" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <field name="employeeNumber" class="java.lang.String"/>
    <field name="employeeName" class="java.lang.String"/>
    <field name="employeeAddress" class="java.lang.String"/>
    <field name="employeeSalary" class="java.lang.String"/>
    <columnHeader>
    <band height="30">
        <staticText>
                <reportElement x="106" y="5" width="100" height="20"/>
                <textElement>
                        <font size="8" isBold="true"/>
                </textElement>
                <text><![CDATA[Employee Number]]></text>
        </staticText>
        <staticText>
                <reportElement x="218" y="5" width="100" height="20"/>
                <textElement>
                        <font size="8" isBold="true"/>
                </textElement>
                <text><![CDATA[Employee Name]]></text>
        </staticText>
        <staticText>
                <reportElement x="328" y="5" width="100" height="20"/>
                <textElement>
                        <font size="8" isBold="true"/>
                </textElement>
                <text><![CDATA[Employee Address]]></text>
        </staticText>
        <staticText>
                <reportElement x="439" y="5" width="100" height="20"/>
                <textElement>
                        <font size="8" isBold="true"/>
                </textElement>
                <text><![CDATA[Employee Salary]]></text>
        </staticText>
        <staticText>
                <reportElement x="6" y="5" width="89" height="20"/>
                <textElement>
                        <font size="8" isBold="true"/>
                </textElement>
                <text><![CDATA[Sr. Number]]></text>
        </staticText>
    </band>
    </columnHeader>
    <detail>
    <band height="26">
        <textField>
                <reportElement x="106" y="6" width="100" height="20"/>
                <textElement>
                        <font size="8"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{employeeNumber}]]></textFieldExpression>
        </textField>
        <textField>
                <reportElement x="218" y="6" width="100" height="20"/>
                <textElement>
                        <font size="8"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{employeeName}]]></textFieldExpression>
        </textField>
        <textField>
                <reportElement x="328" y="6" width="100" height="20"/>
                <textElement>
                        <font size="8"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{employeeAddress}]]></textFieldExpression>
        </textField>
        <textField>
                <reportElement x="439" y="6" width="100" height="20"/>
                <textElement>
                        <font size="8"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{employeeSalary}]]></textFieldExpression>
        </textField>
        <textField>
                <reportElement x="6" y="6" width="89" height="20"/>
                <textElement>
                        <font size="8"/>
                </textElement>
                <textFieldExpression><![CDATA[$V{REPORT_COUNT}]]></textFieldExpression>
        </textField>
    </band>
    </detail>
    </jasperReport>

    We have finished the design phase of report, now let us move on to the Java side.
    Step 1:
    Create new project by selecting the simple Java Application Setting and add all the necessary libraries which is described in our Jasper Tutorial.

    Step 2:
    We have to display the multiple records by using Java POJO classes, so create a new class with name Employee and create the variables with the same name and datatype which was we used in .jrxml file. Create getter and setter method for each variable.

    package com.refermycode.mypackage;
    /*
    * @author Mayur
    */

    public class Employee {
    String employeeNumber = "";
    String employeeName = "";
    String employeeAddress = "";
    String employeeSalary = "";
    public String getEmployeeAddress() {
    return employeeAddress;
    }
    public void setEmployeeAddress(String employeeAddress) {
    this.employeeAddress = employeeAddress;
    }
    public String getEmployeeName() {
    return employeeName;
    }
    public void setEmployeeName(String employeeName) {
    this.employeeName = employeeName;
    }
    public String getEmployeeNumber() {
    return employeeNumber;
    }
    public void setEmployeeNumber(String employeeNumber) {
    this.employeeNumber = employeeNumber;
    }
    public String getEmployeeSalary() {
    return employeeSalary;
    }
    public void setEmployeeSalary(String employeeSalary) {
    this.employeeSalary = employeeSalary;
    }
    }

    Step 3:
    In main class add the following code to generate the PFD.

    package com.refermycode.mypackage;

    import java.io.*;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import net.sf.jasperreports.engine.*;
    import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
    import net.sf.jasperreports.engine.design.JasperDesign;
    import net.sf.jasperreports.engine.xml.JRXmlLoader;

    /*
    * @author Mayur
    */

    public class JasperTutorial2 {

    public static List addEmployeeInfo() {
    List employeeList = new ArrayList();

    Employee employee = new Employee();
    employee.setEmployeeNumber("1001");
    employee.setEmployeeName("Ajit");
    employee.setEmployeeAddress("Latur");
    employee.setEmployeeSalary("40,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1002");
    employee.setEmployeeName("Amit");
    employee.setEmployeeAddress("Aurangabad");
    employee.setEmployeeSalary("50,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1004");
    employee.setEmployeeName("Aniket");
    employee.setEmployeeAddress("Nashik");
    employee.setEmployeeSalary("50,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1004");
    employee.setEmployeeName("Anup");
    employee.setEmployeeAddress("Pune");
    employee.setEmployeeSalary("60,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1005");
    employee.setEmployeeName("Hitesh");
    employee.setEmployeeAddress("Akurdi");
    employee.setEmployeeSalary("50,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1006");
    employee.setEmployeeName("Kuldeep");
    employee.setEmployeeAddress("Hyderabad");
    employee.setEmployeeSalary("60,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1007");
    employee.setEmployeeName("Mayur");
    employee.setEmployeeAddress("Vishrantwadi");
    employee.setEmployeeSalary("50,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1008");
    employee.setEmployeeName("Omkar");
    employee.setEmployeeAddress("Rajgurunagar");
    employee.setEmployeeSalary("30,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1009");
    employee.setEmployeeName("Tushar");
    employee.setEmployeeAddress("Kopargaon");
    employee.setEmployeeSalary("60,000");
    employeeList.add(employee);

    employee = new Employee();
    employee.setEmployeeNumber("1010");
    employee.setEmployeeName("Vijay");
    employee.setEmployeeAddress("Shirdi");
    employee.setEmployeeSalary("60,000");
    employeeList.add(employee);

    return employeeList;
    }

    public static void main(String[] args) throws FileNotFoundException {
    try {
    InputStream inputStream = new FileInputStream("C:/JasperTutorial2/src/com/refermycode/mypackage/Report2.jrxml");
    JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

    HashMap parameters = new HashMap();
    List employeeList = addEmployeeInfo();
    JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(employeeList);
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
    JasperExportManager.exportReportToPdfFile(jasperPrint, "C:/test_jasper.pdf");
    } catch (JRException ex) {
    Logger.getLogger(JasperTutorial2.class.getName()).log(Level.SEVERE, null, ex);
    }
    }
    }

    If you want to know how above code is work then refer the page of our Tutorials from Here.

    When we execute above code then Jasper will generate the desire output with help of Java POJO classes and collection framework.

    Following is the generated sample pdf of our above code.

    Blog1_2

    This is the way to generate Numerical Sequence for records in Jasper Report.

    Now the actual implementation of this blog is started from here.

    To generate alphabetical sequence for records,We need to made some changes in Jasper as well as Java. So let us make changes in Java code first.

    Create one ArrayList which include the Alphabets which we need to print instead of Number and put it into the map of parameters with the name “characterList”.

    List characters = new ArrayList(26);
    for (char c = ‘A’; c &lt;= ‘Z’ ; c++) {
    characters.add(String.valueOf(c));
    }
    parametersMap.put("charactersList", characters);

    That is sufficient from Java code. Now we also need to made some changes in design. So add the parameter in the design as shown in following screenshot and give name same as given in Java code, i.e. “characterList”.

    Blog1_3

    Replace the expression of text field which print the sequence number by following code as shown in following screenshot.

    $P{charactersList}.get(($V{REPORT_COUNT}1)%26)

    This code will replace the numeric values by alphabets and after 26 character it will start sequence from first alphabet again.

    Blog1_4

    After this run the program and find the generated PDF which includes the alphabetical sequence which is set in ArrayList ‘charactersList’ as shown in following screenshot.

    Blog1_5

    Hope this blog is help you to generate custom sequence in your Jasper Report.

    Please don’t forget to comment your feedback for this post 🙂