Monday, March 31, 2014

Is Interface going to replace Abstract Class - Java 8?

In Java 8, interface is altered so that it can have abstract methods and default methods. With this alteration, the methods we used to put in an abstract class can now be moved to the interface. Does this mean that we do not need abstract class anymore?

With interfaces in java 8 can have default and abstract methods, it is likely that we are going to create less abstract classes. However, it is unlikely that abstract class is going to be totally replaced by interface, because in an interface, you cannot put private, protected, non-static, non-final fields and non-static and non-default methods.

For example, you have a Car interface:

      public interface Car {
              public void run();
              public String getCarType();

              default boolean readyToDrive() {
                    return  true;
             }
      }

Surely, you don't want to put the carType field in the interface, which automatically becomes final and static. If you can only implement the run method when you are dealing with a specific type of car, you need an abstract class to implement the getCarType method.

The advantages of using interface over abstract class
An interface can extends one or multiple other interfaces, but cannot extends any class.
A class can implement one or multiple interfaces, but can only extends one class.

The advantages of using abstract class over interface
An abstract class can have protected and private fields and methods.

--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

JavaFX - Add video to the screen

To add a Video to your JavaFX screen, first create a Media using the video file, then create a MediaPlayer using the Media, and create a MeidaView using the created MediaPlayer or set the MediaPlayer of your MediaView to the created MediaPlayer. Finally add the MediaView to your scene.

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;

public class VedioTest extends Application {
 
    @Override
    public void start(Stage primaryStage) {
        //Creating the Media
        //Either use absolute path of the audio clip or it should be in the same place
        //where the Class used to load it is located
        //Here the Kalimba.mp3 should be in the same directory as the VedioTest
        Media media = new Media(VedioTest.class.getResource("TestVideo.mp4").toString());
     
        //Creating the MediaPlayer
        final MediaPlayer mediaPlayer = new MediaPlayer(media);
//        Make the video automatically play forever
//        mediaPlayer.setAutoPlay(true);
//        mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
     
        //Creating the MediaView
        MediaView mediaView = new MediaView(mediaPlayer);
     
        Button btn = new Button();
        btn.setText("Play Video");
        btn.setOnAction(new EventHandler<ActionEvent>() {
         
            @Override
            public void handle(ActionEvent event) {
                //Call one of the methods of MediaPlayer such as
                //play(), pause(), and stop()
                mediaPlayer.play();
            }
        });
     
        //Add the MediaView to the scene
        Pane root = new Pane();
        btn.relocate(50, 200);
        root.getChildren().addAll(mediaView, btn);
//        root.getChildren().add(btn);
     
        Scene scene = new Scene(root, 300, 250);
     
        primaryStage.setTitle("Video!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
 
----------------------------------------------------------------------------------------------------------  

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, March 28, 2014

Stream and aggregate operations in Java 8

In java 8, the List interface has a new method, stream(), which returns a Stream object. The Stream interface has a collection of methods, such as filter(), sorted(), map(), find(), sum(), reduce() and match(), that return the Stream itself after its operation. This makes it possible to call these methods one after another like they are a pipeline.

For example, to select all the women who are older than 18 from a collection of people:
      List<Person> peopleList = <your collection of people>
      List<Person> womenOlderThan18 = peopleList.stream()
                         .filter(p -> p.getGender() == female && p.getAge() > 18)
                         .sorted(Comparator.comparingInt(Person::getAge))
                         .collect(Collectors.toList());

The collect() function closes the pipeline and converts the Stream to a Collection. For example, the following code will return a Map that maps the department Id to a group of people.

      Map<Integer, List<Person>> deptToPepleMap = peopleList.stream()
                   .collect(Collectors.groupingBy(Person::getDepartmentId));

The map() function of Stream tells the function that follows it what to operate on. For example, to get the sum of the ages of all the people in the collection.

      int totalAge = peopleList.stream()
            .map(Person::getAge)
            .sum();

To get a collection of all the IDs.

      List<Integer> ids = peopleList.stream()
            .map<Person::getId)
            .sorted()
            .collect(Collectors.toList());

Many of the Stream operations perform the same functions as the corresponding aggregate functions in a SQL statement, they are therefore also referred to as aggregate operations.

-------------------------------------------------------------------------------------------------------------

                        

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, March 27, 2014

Convert long to integer in Java

In java, a long value has 64 bits and it is a signed value ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 inclusively. An int value has 32 bits and it is also a signed value ranging from -2,147,483,648 to 2,147,483,647 inclusively. 

To convert a long value that is in the range of -2,147,483,648 to 2,147,483,647, you can directly cast it to int.

      long a = 33444556L;
      int b = (int)a;

However, if the long value is out of the -2,147,483,648 to 2,147,483,647 range, casting returns -1.

Here is a sample code for testing the conversion.

public class LongToIntegerTest {
    public static void main(String[] args){
        long x1 = 2147483647L;
        int y1 = (int)x1;
        Long x12 = new Long(x1);
        int y12 = x12.intValue();
        
        long x2 = 9223372036854775807L;
        int y2 = (int)x2;
        Long x22 = new Long(x2);
        int y22 = x22.intValue();
        
        System.out.println("y1 = "+y1);
        System.out.println("y12 = "+y12);
        System.out.println("y2 = "+y2);
        System.out.println("y22 = "+y22);
    }

}

Output:
y1 = 2147483647
y12 = 2147483647
y2 = -1
y22 = -1

-----------------------------------------------------------------------------------------------------------------------

                        

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Java enum

Enum in Java is a special class type which serves as a data structure that holds a collection of objects having same structures. The data in an enum is static and final, they cannot be modified. Enum has a default constructor that takes no arguments.

For example:

       public enum Month {
             JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
             JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
       }

is a simple enum defines the type of Month. Each element in the enum is called an enum constant. The enum can be used as shown below.

      public class EnumTest {
            public static void main(String[] args){
                  Month theMonth = Month.DECEMBER;
                  System.out.println(theMonth);
                  System.out.println(Month.valueOf("DECEMBER"));

                  //The ordinal method returns the position of an enum constant in the enum.
                  //The position of the first enum constant is zero.
                  System.out.println(Month.MARCH.ordinal());

                  Month[] months = Month.values();
                  for (Month month : months) {
                        System.out.println(month);
                 }
            }
      }

      The output of the above code:

      DECEMBER
      DECEMBER
      2
      JANUARY
      FEBRUARY
      MARCH
      APRIL
      MAY
      JUNE
      JULY
      AUGUST
      SEPTEMBER
      OCTOBER
      NOVEMBER
      DECEMBER

Each enum constant can have its own values. In the above Month enum, each month has the number of days and number of weekends in it. To have these values in the Month enum, you must create a constructor for the enum that matches the declaration of your enum constants.

      public enum Month {
            JANUARY(31,5),
            FEBRUARY(28,4),
            MARCH(31,5),
            APRIL(30,4),
            MAY(31,5),
            . . . . . .
           DECEMBER(31,4);
 
          //The fields for the values
           private final int days;
           private final int weekends;
 
          //Create a constructor that matches the type
           Month(int days, int weekends) {
                this.days = days;
                this.weekends = weekends;
           }
 
          //Enums can also have methods
            public int getDays() {return days;}
            public int getWeekends() {return weekends;}
 
            public int getWorkingDays() {
                return days-weekends;
            }
      }

       public class EnumTest {
             public static void main(String[] args){
                   Month theMonth = Month.FEBRUARY;
                   System.out.println("Working days in February="+theMonth.getWorkingDays());
             }
      }

      The output is:

      Working days in February=24

-------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, March 25, 2014

Lambda Expressions and functional interface in Java 8

Lambda Expression is a new feature added to Java 8. It simplifies code by passing functions/methods directly to a method as parameters. It is used for implementing interfaces that have only one abstract method, known as functional interfaces. Since the interface has only one abstract method, when a method from another object has an argument that is the type of this interface, a lambda expression can be used to put the implementation of the functional interface, the code for overriding the abstract method of the interface, in the place of the argument of the method.

The syntax of Lambda Expressions

1. A parenthesis within which has a comma-separated list of objects/primitives which are the parameters of the abstract method that this Lambda Expression is overriding. If there is only one item in the parenthesis, the parenthesis can be removed. If the abstract method takes no argument, the empty parenthesis "()" (without the quotes) is used.

2. The right headed arrow ( -> ) that separates the parameters from the method implementation.

3. The body that implements the logic of the method.

For example:
       (int a, int b) -> a > b && (a - b) < 50
can be the implementation of such a functional interface:
       public interface Calculator {
              public boolean test(int a, int b);
      }
If you have the following code that uses the Calculator as a parameter:
      public class DecisionMaker {
            public Person getThe RightPerson (Person person1,
                                                                Person person2,
                                                               Calculator calculator) {
                    int age1 = person1.getAge(), age2 =  person2.getAge();

                   if (calculator.test(age1, age2)) {
                         return person1;
                  } else {
                         return person2;
                  }
            }
      }
Since Calculator is an interface, before Java 8, you have to create a class to implement this interface before you can use it, and you pass an instance of the implementing class to the method. However, with Lambda Expression, the implementing class can be omitted.
   
Without using Lambda Expression:
       public class MyCalculator implements Calculator {
               public boolean test (int a, int b) {
                      System.out.println("Without using lambda expression."); 
                      return (a > b && (a - b) < 50);
               }
       }
     
       DecisionMaker dm = new DecisionMaker();
       Person rightPerson = dm.getTheRightPerson(
                                                person1,
                                                person2,
                                                new MyCalculator());

Using Lambda Expression:
       DecisionMaker dm = new DecisionMaker();
       Person rightPerson = dm.getTheRightPerson(
                                                person1,
                                                person2,
                                                (int a, int b) -> {System.out.println("Using lambda expression."); return a > b && (a - b) < 50;});

Another Example

Here is another example of using Lambda Expressions. Every year, in your company, you give a special prize to those employees whose performance is over 800 and whose team's performance is over 600. You can use the following code to get a list of those that qualify for the prize.

//Create the functional interface.
//A functional interface is an interface that contains only one abstract method.
//It may have one or more static and default methods.
public interface Qualifier {
      public boolean isQualified (Employee employee, Team team);
}

//The class that does the screening
public class SpecialPrizeScreener {
      public List<Employee> getSpecialPrizeWinners(List<Employee> allEmployees,
                                          List<Team> teams,
                                          Qualifier qualifier) {

            List<Employee> result = new ArrayList<Employee>();
         
            for (Employee employee : allEmployees){
                  for (Team team : teams) {
                         if (team.contains(employee)) {
                                if (qualifier.isQualified(employee, team) {
                                       result.add(employee);
                                }
                         }
                   }
   }
            return result;
      }

      public static void main(String[] args) {
            SpecialPrizeScreener screener = new SpecialPrizeScreener();
            List<Employee> allEmployees = <your method to get all your employees>;
            List<Team> teams = <your method to get all the teams>;

            //The method name can be omitted in Java 8 when implementing a functional interface.
            //Thus, the Lambda Expression can be used in implementing the functional interface
            //and used directly as a parameter of the method call.
            List<Employee> specialPrizeWinners = screener.getSpecialPrizeWinners (
                        allEmployees,
                        teams,
                        (Employee employee, Team team) -> employee.getPerformance() > 800
                                                        && team.getPerformance() > 600);

      }
}

Using generic functional interface

//Create the functional interface that takes generics
public interface Qualifier<K, V> {
      public boolean isQualified (K param1, V param2);
}

//Modify the getSpecialPrizeWinners method in the SpecialPrizeScreener class to let the Qualifier take Employee and Team as its generic types.

      public List<Employee> getSpecialPrizeWinners(List<Employee> allEmployees,
                                          List<Team> teams,
                                          Qulifier<Employee, Team> qualifier)

//In the above Lambda Expression, the parameter types can be omitted.
List<Employee> specialPrizeWinners = screener.getSpecialPrizeWinners (
                        allEmployees,
                        teams,
                        (employee, team) -> employee.getPerformance() > 800
                                                        && team.getPerformance() > 600);

Using multiple Lambda Expressions

//You may use as many as Lambda Expressions in a method wherever it is possible
//You may modify the above code to add another Lambda Expression.

//Using the functional interface Consumer<T> interface
public interface Consumer<T> {
      public void accept(T t);
}


public class SpecialPrizeScreener {
      public void getSpecialPrizeWinners(List<Employee> allEmployees,
                                          List<Team> teams,
                                          List<Employee> result,
                                          Qulifier qualifier,
                                          Consumer<Employee> consumer) {

            for (Employee employee : allEmployees){
                  for (Team team : teams) {
                         if (team.contains(employee)) {
                                if (qualifier.isQualified(employee, team) {
                                       consumer.accept(employee);
                                }
                         }
                   }
   }
      }

      public static void main(String[] args) {
            SpecialPrizeScreener screener = new SpecialPrizeScreener();
            List<Employee> allEmployees = <your method to get all your employees>;
            List<Team> teams = <your method to get all the teams>;
            List<Employee> result = new ArrayList<Employee>();

            //implementing the additional Lambda Expression
            screener.getSpecialPrizeWinners (
                        allEmployees,
                        teams,
                        result,
                        (employee, team) -> employee.getPerformance() > 800
                                                        && team.getPerformance() > 600,
                        employee -> result.add(employee));

      }
}

------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, March 19, 2014

The Oracle DUAL table

The DUAL table in Oracle database is a technical table with one column named DUMMY (data type VARCHAR2(1)) and one row of data of value 'x' in it. So SELECT * FROM DUAL will give the following result.

DUMMY
-----------
x

The DUAL table is often used to satisfy the SQL syntax that a query must have at least the SELECT and FROM clauses.

For example
SELECT 'My Answer' FROM DUAL;
returns 'My Answer' as the value.

SELECT 'My Answer' || ' Your Answer' FROM DUAL;
returns 'My Answer Your Answer' as the value.

SELECT 1345 FROM DUAL;
returns 1345 as the value.

SELECT 5*20 FROM DUAL;
returns the calculation result (100) as the value. Variance kind of calculations can be performed here.

SELECT SYSDATE FROM DUAL;
returns the current date

SELECT USER FROM DUAL;
returns the user ID that is used to connect to the database.

SELECT <your sequence>.nextval FROM DUAL;
returns the next value from the sequence.

-------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


Friday, March 14, 2014

JavaFX - AudioClip

To add an AudioClip to your JavaFX screen, create an AudioClip and call its method play().

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.media.AudioClip;
import javafx.stage.Stage;

public class AudioClipTest extends Application {
 
    @Override
    public void start(Stage primaryStage) {
        //Creating the AudioClip
        //Either use absolute path of the audio clip or it should be in the same place
        //where the Class used to load it is located
        //Here the Kalimba.mp3 should be in the same directory as the AudioClipTest
        final AudioClip audioClip = new AudioClip(AudioClipTest.class.getResource("Kalimba.mp3").toString());
     
        Button btn = new Button();
        btn.setText("Song: Kalimba");
        btn.setOnAction(new EventHandler<ActionEvent>() {
         
            @Override
            public void handle(ActionEvent event) {
                //calling the AudioClip's play method
                audioClip.play();
            }
        });
     
        StackPane root = new StackPane();
        root.getChildren().add(btn);
     
        Scene scene = new Scene(root, 300, 250);
     
        primaryStage.setTitle("My favorate songs!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
 
--------------------------------------------------------------------------------------------------------------  

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

DynamicReports in java (5) - subreport and page break

The subreport function allows multiple reports to be included into one report one after another.

public class SubreportTest {
       private StyleBuilder bold;
       private StyleBuilder centeredBold;
       private StyleBuilder columnTitleStyle;
       private StyleBuilder columnStyle;

       private JasperReportBuilder reportBuilder;

      public SubreportTest() {
            bold = Styles.style().bold();
            centeredBold = Styles.style(bold)
                    .setHorizontalAlignment(HorizontalAlignment.CENTER);
            columnTitleStyle = Styles.style(centeredBold)
                    .setBackgroundColor(Color.LIGHT_GRAY)
                    .setBorder(Styles.pen1Point());
            columnStyle = Styles.style()
                    .setHorizontalAlignment(HorizontalAlignment.LEFT)
                    .setLeftIndent(4)
                    .setBottomPadding(5);

            build();
      }

       public void build() {
              //Creating the subreport
              SubreportExpression subreportExpress = new SubreportExpression();
              SubreportBuilder subreport = Components.subreport(subreportExpress);
              subreport.setDataSource(new SubreportDataSourceExpression());
              reportBuilder = DynamicReports.report();
           
              //Formatting the subreports
              //Using default page break and setting the gap between subreports to 20
              reportBuilder.detail(subreport, Components.verticalGap(20));
              //Beginning each subreport on a new page
              //reportBuilder.detail(subreport, Components.pageBreak());
               //Only having a page break at a subreport
               //reportBuilder.detail(subreport, Components.pageBreak().setPrintWhenExpression(new PageBreakExpression()));
               //No page break
               //reportBuilder.ignorePagination();

               //Setting the page header (the title to be displayed on top of each page)
               reportBuilder.pageHeader(Components.text("Comprehensive Report").setStyle(centeredBold));
               reportBuilder.pageHeader(Components.text("Statistics of Market Development").setStyle(centeredBold));
               reportBuilder.pageHeader(Components.horizontalList(Components.text("Date: " + new Date().toString()),
                Components.filler().setFixedWidth(420),
                Components.text("Pay Attention Please")));

              //Setting the page footer
               reportBuilder.pageFooter(Components.horizontalFlowList().add(Components.text("Page "))
                .add(Components.pageNumber())
                .setStyle(bold));

              //Setting the number of subreports
              reportBuilder.setDataSource(new JREmptyDataSource(2));

             reportBuilder.show();
             reportBuilder.toPdf(new FileOutputStream(new File(<fileName>)));
     }
   
      private class SubreportExpression extends AbstractSimpleExpression<JasperReportBuilder> {
            public JasperReportBuilder evaluate(ReportParameters reportParameters) {
                    int masterRowNumber = reportParameters.getReportRowNumber();
         
                    JasperReportBuilder report = DynamicReports.report();
                    //DynamicReports subreport row starts from 1 instead of 0
                    if (masterRowNumber == 1){
                           report.columns(Columns.column("Col 1", "col1Data", DataTypes.stringType()),
                                                   Columns.column("Col 2", "col2Data", DataTypes.stringType()));
                           report.setColumnTitleStyle(columnTitleStyle.setBottomBorder(Styles.penDashed()));
                          report.setColumnStyle(columnStyle);
                          report.highlightDetailEvenRows();
                    } else if (masterRowNumber == 2){
                           report.columns(Columns.column("Column 1", "col3Data", DataTypes.stringType()),
                                                   Columns.column("Column 2", "col4Data", DataTypes.stringType()));
                           report.setColumnTitleStyle(columnTitleStyle.setBottomBorder(Styles.penDashed()));
                          report.setColumnStyle(columnStyle);
                          report.highlightDetailEvenRows();
                    }
             }
              return report;
      }

       private class SubreportDataSourceExpression extends AbstractSimpleExpression<JRDataSource> {
              //private ArrayList<DRDataSource> dataSourceArray;
     
              //public SubreportDataSourceExpression(ArrayList<DRDataSource> dataSourceArray){
                      // super();
                       // this.dataSourceArray = dataSourceArray;
              //}
     
              public JRDataSource evaluate(ReportParameters reportParameters) {
                      int masterRowNumber = reportParameters.getReportRowNumber();
                      DRDataSource dataSource;
                      if (masterRowNumber == 1) {
                             dataSource = new DRDataSource("col1Data", "col2Data");
                             dataSource.add("Apple", "Sweet Fruit");
                             dataSource.add("Lemon", "Sour Fruit");
                      } else if (masterRowNumber == 2) {
                             dataSource = new DRDataSource("col3Data", "col4Data");
                             dataSource.add("Diamond", "Transparent");
                             dataSource.add("Ruby", "Red");
                      }
                      return dataSource;
                     // return dataSourceArray.get(masterRowNumber-1);
              }
       }

        private class PageBreakExpression extends AbstractSimpleExpression<Boolean> {
                public Boolean evaluate(ReportParameters reportParameters) {
                       //Only having a page break after the first subreport
                        if (reportParameters.getReportRowNumber() == 1) {
                                return true;
                        } else {
                                return false;
                        }
               }
        }
}

             Previous<

---------------------------------------------------------------------------------------------------------------      

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

References:


Tuesday, March 11, 2014

DynamicReports in java (3) - Concatenating reports

The concatenating function of DynamicReports allow multiple reports to be included into one single document. Each report starts on a new page with its own page dimension.


import java.io.File;
import net.sf.dynamicreports.jasper.builder.export.Exporters;
import static net.sf.dynamicreports.report.builder.DynamicReports.concatenatedReport;
import net.sf.dynamicreports.report.exception.DRException;

public class ConcatenatedReportTest {
    public ConcatenatedReportTest() {
        build();
    }
 
    public void build() {
        try {
            concatenatedReport().setContinuousPageNumbering(true)
                .concatenate(<JasperReportBuilder1>, <JasperReportBuilder2>)
                .toPdf(Exporters.pdfExporter(new File("C:/MyReport.pdf")));
        }catch(DRException e){
            e.printStackTrace();
        }
    }
}

            Previous<      >Next
       
--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

References:

1. DynamicReports in Java (1) - Using defined data type and the steps for a basic report
2.DynamicReports in Java (2) - Using adhoc data types
3. DynamicReports in java (4) - Setting/formatting the title
4. DynamicReports in java (5) - subreport and page break
5. Getting started
6. Reporting In Java Using DynamicReports And JasperReports

DynamicReports in java (4) - Setting/formatting the title

       JasperReportBuilder report = DynamicReports.report();

1. Setting a simple title for the report

      report.title(Components.text("The Comprehensive Report")
              .setHorizontalAlignment(HorizontalAlignment.CENTER));

2. Using styles

       StyleBuilder titleStyle = Styles.style().bold()
              .setHorizontalAlignment(HorizontalAlignment.CENTER)
              .setFontSize(14)
              .setBackgroundColor(Color.LIGHT_GRAY)
              .setBorder(Styles.pen1Point());

        report.setTitleStyle(titleStyle);

3. Setting a multiple line title

       report.title(Components.text("Statistic Report")); //first line
       report.title(Components.text("Longevity in Populations));//second line
       

4. Setting a title with multi-components on one line

       SimpleDateFormat formater = new SimpleDateFormat("MM/dd/YY");

      report.title(Components.horizontalList(Components.text("Date: "+ formater.format(new Date()),
                Components.filler().setFixedWidth(420),
                Components.text("First Part"))
              .setStyle(Styles.style(bold).setHorizontalAlignment(HorizontalAlignment.LEFT)));

5. Print Title on top of each page

      Use report.pageHeader(ComponentBuilder... component) instead of report.title(ComponentBuilder... component)

            Previous<      >Next

-------------------------------------------------------------------------------------------------------------
          
                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

References:

DynamicReports in Java (2) - Using ad hoc data types

1. Create a simple tabular report

      import net.sf.dynamicreports.adhoc.AdhocManager;
      import net.sf.dynamicreports.adhoc.configuration.AdhocColumn;
      import net.sf.dynamicreports.adhoc.configuration.AdhocConfiguration;
      import net.sf.dynamicreports.adhoc.configuration.AdhocReport;
      import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
      import net.sf.dynamicreports.report.builder.component.Components;
      import net.sf.dynamicreports.report.constant.HorizontalAlignment;
      import net.sf.dynamicreports.report.datasource.DRDataSource;
      import net.sf.dynamicreports.report.exception.DRException;
      import net.sf.jasperreports.engine.JRDataSource;

      public class AdhocReportTest1 {
           public AdhocReportTest1() {
                build();
           }
 
           public void build() {
               //Creating the AdhocConfiguration for the report
               AdhocConfiguration config = new AdhocConfiguration();
               AdhocReport report = new AdhocReport();
               config.setReport(report);

               //Creating the columns for the report
               AdhocColumn column = new AdhocColumn();
              column.setName("Name");
              report.addColumn(column);
     
              column = new AdhocColumn();
              column.setName("Price");
               report.addColumn(column);
     
              column = new AdhocColumn();
              column.setName("Quantity Ordered");
              report.addColumn(column);
     
              try {
                  //Can save the configuration and reload in the future
//                  AdhocManager.saveConfiguration(config, new FileOutputStream(new File("c:/temp/configuration.xml")));
//                  AdhocConfiguration loadedConfiguration = AdhocManager.loadConfiguration(new FileInputStream("c:/temp/configuration.xml"));

                  JasperReportBuilder reportBuilder = AdhocManager.createReport(config.getReport());

                  //Setting the title of the report
                   reportBuilder.addTitle(Components.text("List of Orders\n------------")
                          .setHorizontalAlignment(HorizontalAlignment.CENTER));

                  //Setting the data source
                  reportBuilder.setDataSource(createDataSource());
                  reportBuilder.show();
               } catch (DRException e){
                      e.printStackTrace();
//              } catch (FileNotFoundException e) {
//                   e.printStackTrace();
               }
          }
 
          private JRDataSource createDataSource() {
              DRDataSource dataSource = new DRDataSource("Name", "Price", "Quantity Ordered");
              dataSource.add("-----", "-----", "-----");
              dataSource.add("Apple", 1.29, 120.00);
              dataSource.add("Apple", 1.69, 150);
              dataSource.add("Orange", 0.99, 130);
              dataSource.add("Orange", 0.96, 100);
              dataSource.add("Mange", 2.99, "three hundred");
              return dataSource;
          }
 
          public static void main(String[] args){
              new AdhocReportTest1();
          }
      }

2. Create a customized tabular report

import net.sf.dynamicreports.adhoc.AdhocManager;
import net.sf.dynamicreports.adhoc.configuration.AdhocCalculation;
import net.sf.dynamicreports.adhoc.configuration.AdhocColumn;
import net.sf.dynamicreports.adhoc.configuration.AdhocConfiguration;
import net.sf.dynamicreports.adhoc.configuration.AdhocGroup;
import net.sf.dynamicreports.adhoc.configuration.AdhocReport;
import net.sf.dynamicreports.adhoc.configuration.AdhocSort;
import net.sf.dynamicreports.adhoc.configuration.AdhocStyle;
import net.sf.dynamicreports.adhoc.configuration.AdhocSubtotal;
import net.sf.dynamicreports.adhoc.configuration.AdhocSubtotalPosition;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;

public class AdhocReportTest2 {
    public AdhocReportTest2() {
        build();
    }

    public void build() {
        //Creating the AdhocConfiguration for the report
        AdhocConfiguration config = new AdhocConfiguration();
        AdhocReport report = new AdhocReport();
        config.setReport(report);

        AdhocColumn column = new AdhocColumn();
        column.setName("Price");
        report.addColumn(column);

        column = new AdhocColumn();
        column.setName("Quantity");
        report.addColumn(column);
     
        //Creating group by
        AdhocGroup group = new AdhocGroup();
        group.setName("Name");
        report.addGroup(group);
     
        //Creating the subtotals
        AdhocSubtotal subtotal = new AdhocSubtotal();
        subtotal.setGroupName("Name");
        subtotal.setLabel("Average Price");
        subtotal.setName("Price");
        subtotal.setCalculation(AdhocCalculation.AVERAGE);
        subtotal.setPosition(AdhocSubtotalPosition.GROUP_FOOTER);
        report.addSubtotal(subtotal);
     
        subtotal = new AdhocSubtotal();
        subtotal.setGroupName("Name");
        subtotal.setName("Quantity");
        subtotal.setLabel("Total ordered");
        subtotal.setCalculation(AdhocCalculation.SUM);
        subtotal.setPosition(AdhocSubtotalPosition.GROUP_FOOTER);
        report.addSubtotal(subtotal);
     
        //Creating sort by
        AdhocSort sort = new AdhocSort();
        sort.setName("Name");
        report.addSort(sort);

        try {
            JasperReportBuilder reportBuilder = AdhocManager.createReport(config.getReport());

            //Setting the title of the report
            reportBuilder.addTitle(Components.text("Summary of Orders")
                    .setHorizontalAlignment(HorizontalAlignment.CENTER));

            //Setting the data source
            reportBuilder.setDataSource(createDataSource());
            reportBuilder.show();
        } catch (DRException e) {
            e.printStackTrace();
        }
    }

    private JRDataSource createDataSource() {
        DRDataSource dataSource = new DRDataSource("Name", "Price", "Quantity");
        dataSource.add("Apple", 1.29, 120);
        dataSource.add("Apple", 1.69, 150);
        dataSource.add("Orange", 0.99, 130);
        dataSource.add("Orange", 0.96, 100);
        dataSource.add("Mange", 2.99, 300);
        return dataSource;
    }

    public static void main(String[] args) {
        new AdhocReportTest2();
    }
}

          Previous<      >Next

---------------------------------------------------------------------------------------------------------------
       
                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.
--------------------------------------------------------------------------------------------------------------------------

References:

1.DynamicReports in Java (1) - Using defined data type and the steps for a basic report
2. DynamicReports in java (3) - Concatenating reports
3. DynamicReports in java (4) - Setting/formatting the title
4. DynamicReports in java (5) - subreport and page break
5. Getting started
6. Reporting In Java Using DynamicReports And JasperReports

Monday, March 10, 2014

DynamicReports in Java (1) - Using defined data type and the steps for a basic report

DynamicReports, based on JasperReports,  is a tool to view the data in your data source which can be your database connected through JDBC, dynamically generated data, or other source. The report can be viewed in JasperReports Viewer and be written to your hard drive as PDF, HTML, XML, DOCX and other types of files. The report can be formulated in the form of a table, one of the many styles of charts, or other styles. Following are the steps to generate a simple tabular report using  a table in your database as the data source.

1. Download DynamicReports from its official website and add it to your classpath or project library. You need the jars in the dist and the lib directories.

2. Create and run the code. Following is a sample code.

import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;

public class Test {
    String url = "<your JDBC url>";
    String driver = "<your JDBC driver>";
    String user = "<your username>";
    String passwd = "<your password>";

    public Test() {
          build();
     }

    public void build() {
        Connection conn = null;
        try {
            conn = getConnection();

            //Creating the report
            JasperReportBuilder report = DynamicReports.report();
             report.setPageFormat(PageType.LETTER);

             //Creating the columns
             //Here "Price" is the column name on report
             //"price" is the data source column name
             TextColumnBuilder<Float> priceColumn = Columns.column("Price", "price", DataTypes.floatType());
             TextColumnBuilder<Integer> quantityOrderedColumn = Columns.column("Quantity Ordered", "quantityOrdered", DataTypes.integerType());
            report.columns(Columns.columnRowNumberColumn("Item"),
                  Columns.column("Name", "name", DataTypes.stringType()),
                  priceColumn,
                  quantityOrderedColumn
              );

            //Styles
            StyleBuilder bold = Styles.style().bold();
            StyleBuilder centeredBold = Styles.style(bold)
                    .setHorizontalAlignment(HorizontalAlignment.CENTER);
            StyleBuilder columnStyle = Styles.style(centeredBold)
                    .setBackgroundColor(Color.LIGHT_GRAY)
                    .setBorder(Styles.pen1Point());
             StyleBuilder titleStyle = Styles.style(centeredBold)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE)
                    .setFontSize(15);
         
            report.setColumnTitleStyle(columnStyle);
            report.setColumnStyle(Styles.style().setHorizontalAlignment(HorizontalAlignment.CENTER));
            report.highlightDetailEvenRows();

             //Additional columns to hold values derived by caculation
              TextColumnBuilder<BigDecimal> moneyPaidColumn = priceColumn.multiply(quantityOrderedColumn)
                        .setTitle("Amount Paid");
              PercentageColumnBuilder percentPayment = Columns.percentageColumn("Payment %", moneyPaidColumn);
              report.addColumn(moneyPaidColumn);
              report.addColumn(percentPayment);

             //Setting the title of the report
            report.title(Components.text("Test Report")
                        .setStyle(titleStyle));
            report.title(Components.currentDate()
                .setHorizontalAlignment(HorizontalAlignment.LEFT));
       
           //Printing the number of pages at the footer
            report.pageFooter(Components.pageXofY()
                        .setStyle(centeredBold));
         
            //Setting the data source
            report.setDataSource(createDataSource()); 
             //Or using data from database
             //String sql = "select name, price, quantityOrdered from DIAMOND";
            //report.setDataSource(sql, conn);

            //Showing as a JasperReport
            report.show();

            //Writing to the hard drive as a pdf file
            java.io.File file = new java.io.File("C:\\MyReport.pdf");
            report.toPdf(new FileOutputStream(file));

            //Or write as a html file
           // java.io.File file = new java.io.File("C:\\MyReport.html");
           // report.toHtml(new FileOutputStream(file));        

            conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }  
    }

      public Connection getConnection() throws Exception {
        Connection conn = null;
   
        Class.forName(driver);
        conn = DriverManager.getConnection(url, user, passwd);
   
        return conn;
    }

      private JRDataSource createDataSource() {
           DRDataSource dataSource = new DRDataSource("name", "price", "quantityOrdered");
           dataSource.add("Apple", 1.29f, 120);
           dataSource.add("Apple", 1.69f, 150);
            dataSource.add("Orange", 0.99f, 130);
            dataSource.add("Orange", 0.96f, 100);
            dataSource.add("Mange", 2.99f, 300);
            return dataSource;
      }

      public static void main(String[] args) {
            new Test();
      }
}

                                              >Next
       
----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.
-------------------------------------------------------------------------------------------------------------------------

References:

1.DynamicReports in Java (2) - Using adhoc data types
2. DynamicReports in java (3) - Concatenating reports
3. DynamicReports in java (4) - Setting/formatting the title
4. DynamicReports in java (5) - subreport and page break
5. Getting started
6. Reporting In Java Using DynamicReports And JasperReports
7. Report bands