RSS

LambdaJ as an alternative to query out from Collections (Stop Iterations!!)

I remember the first time i was taught Data Structure during my college time, there was a way to generate all data from a collection (ArrayList, LinkedList, etc). At that time, i was thinking that it was the best way to populate the data until a position where i learnt how to build a web application and optimization. It is not optimized at all to iterate all the data everytime we triggered an event (let say ‘key event’ when we type ‘A’ and all data consisting ‘A’ will appear).
Microsoft .NET have LINQ, but how about Java? Don’t worry for all of you, there are a lot also tools to do things like this. I will highlight my current post today for LambdaJ. LambdaJ is a library to manipulate a collections without any iterations. You can also implement a ‘SQL’like syntax into it.

To use LambdaJ, you have to download 3 dependencies library for this :

1. CGLib (download from here)
2. LambdaJ (download from here)
3. Hamcrest Matcher (download from here)
NOTE:for Hamcrest Matcher lib, download the one with keyword all

For example if you have a collections below :


List<String> listOfNames = new ArrayList<String>();
listOfNames.add("Hans");
listOfNames.add("Pricillia");

If you want to merge all the data inside of the list, instead of using for, you can use a method from LambdaJ like below :


package test.lambdaj;

import java.util.List;
import java.util.ArrayList;
import static ch.lambdaj.Lambda.*;

/**
 *
 * @author Hans Kristanto
 */
public class Main {
    
    public static void main(String[] args){
    
        List<String> list = new ArrayList<String>();
        list.add("Hans");
        list.add("Pricillia");
        
        String names = "";
        names = join(list,"-");
        
        System.out.println(names);
    }
}   

The result will be :

Hans-Pricillia

Of course it is not all LambdaJ can do, here come the funkiest stuff :D.

Let say we have this list below given :


List<String> listOfNames = new ArrayList<String>();
listOfNames.add("Orange");
listOfNames.add("Mango");
listOfNames.add("Guava");
listOfNames.add("Banana");
listOfNames.add("Papaya");
listOfNames.add("Strawberry");

You want to populate all data containing letter of ‘o’ into new List, you can do like this below :


package test.lambdaj;

import java.util.List;
import java.util.ArrayList;
import static ch.lambdaj.Lambda.*;
import static org.hamcrest.Matchers.*; //IMPORTANT TO DO A MATCHER STUFF

/**
 *
 * @author Hans Kristanto
 */
public class Main {
    
    public static void main(String[] args){
    
        List<String> listOfNames = new ArrayList<String>();
        listOfNames.add("Orange");
        listOfNames.add("Mango");
        listOfNames.add("Guava");
        listOfNames.add("Banana");
        listOfNames.add("Papaya");
        listOfNames.add("Strawberry");
        
        List<String> listOfNewFruit;
        listOfNewFruit = select(listOfNames, having(on(String.class),containsString("o")));
        
        String names = join(listOfNewFruit,"~");

        System.out.println(names);
    }
}   

And the result will be :

Mango

Awesome is it? It will be much more useful for you if you have a case like you have bunches of data generated from DB for example, but you dont want to periodically retrieve from the DB since the data always the same. This can be much more helpful for you.

You can refer more examples from javaone slides below :
LambdaJ Slides.

PS: This tutorial i highly dedicate it to my beloved future fiance Pricillia Gunawan :)

ENJOY!

 
3 Comments

Posted by on August 6, 2011 in English, Programming

 

Tags: , , , , , , , ,

Enabling GC logs in Apache Tomcat

There are so many way to analyze the performance of Application Server. 1 of those are called GC logs. GC logs is a log to monitor the movement of your application server’s memory usage. GC log is superb to analyze any kind of memory leaks or even analyze your optimization of your application. GC is actually stand for Garbage Collection, method in JVM to collecting all un-used or un-referenced object in memory to free up memory. So, lets get it on!

1. Enabling CATALINA_OPTS option and setting up the GC log enable parameter

You need to enable your CATALINA_OPTS parameter. CATALINA_OPTS is a parameter that allow you to specify a specific option during the startup of your tomcat server, such as the initial parameter for heap space, perm space, and so on. This can be done in 2 ways. In Windows Environment, you can create a new variable in your Environment Variable. Another simpler way, you can go to bin folder of your tomcat directory, find for startup.bat script. Open the script and you can set the CATALINA_OPTS variable. I prefer the second way to be explained since the first one only applicable for Windows user only.
So, open your startup.bat script, and add this code below :

set "CATALINA_OPTS=-Xloggc:log.gc"

at wherever you want (as long as it is put before :end and it is not in between if listing code :D ).
The -Xloggc is parameter for enabling GC logs. and log.gc is the name of file that will contain the log for memory. if you write like this, the GC will be created in bin folder right after server getting started up.

2. Start your apache tomcat

Next step, run your startup.bat. Right after the server getting started up, you will see in your bin folder, there will be a file called log.gc as per screen shot below :

If you can see this file, it means you have succesfully enabling your gc log for your performance monitor.

3. Analyze your GC logs

You might want to analyze your GC log since you have enable it and i’m pretty sure that you dont want to open the file using the editor since the content is such a horrible.
There are a lot of tools to analyze it, 1 sample that i take is HPjmeter, 1 of free application too analyze. You can google it to download 1 copy for you. Once you have installed it, you can drag your log.gc file into it, and you can see several options that you can use. Below is the sample screen shot from HPjmeter based on my log.gc :

GC Log Chart Example

GC Log Chart Example

GC Time Duration

Enjoy!!

 
3 Comments

Posted by on July 22, 2011 in English, Programming

 

Tags: , , , ,

Matrimony in Catholic Perspective

I don’t know why i really get interested at the first time i thinking about this topic. Actually i haven’t get marry yet, but this topic is quite attractive for me, and i believe for any people with the same age with me. Well, i have done some researched about it and would like to give a brief explanation about matrimony in Catholic Perspective.

Based on this link, what is defined with matrimony is :

“Living Fellowship – Among a single Man and a single Woman – That is happened because personal agreement that is unbreakable – and have to be targetted to loving each other, and a family creation – And must be faithfull with one another and can not be separated except by the death.”

From this definition, It is obvious that Matrimony is not only a matrimony. But deeper of that, it has a special meaning for a human, especially a catholic to be fulfilled.

It’s not an issue nowadays that we can see a lot of artists or even an ordinary people are so easy to get married and after several years or even months, they can also easily divorced due to a problem or whatsoever. This is the thing that should be prevented in catholic’s matrimony.

To marry means that 1 man and 1 woman have to love each other, with all their hearts, without forcing, and especially, they have to commit with their matrimony itself. The baseline of matrimony is love. And 1 thing we have to take note is, that the love should be everlasting, since it’s indeed that love is the based of Matrimony. Once again, love is the based ground of Matrimony. 1 man and 1 woman have to maintain their love even they are getting older, and not physically attractive. And also Matrimony is sacred, which means that for 1 single life, matrimony can only be conducted once, and can not be separated except by death (refering back to the definition above). So it is true that 1 single man and 1 single woman have to love, again, have to love each other until the death come. From the definition above also we can see that another purpose of matrimony is, to build a family. This is written also in Genesis chapter 1 verse 28 :

“God blessed them and said to them, “Be fruitful and increase in number; fill the earth and subdue it. Rule over the fish in the sea and the birds in the sky and over every living creature that moves on the ground.”

God said this words during the creation of Human. So, matrimony is to build a family and a family is built on top of matrimony. So, by right it’s impossible to build a family without matrimony (this is 1 thing that the world has distorted the meaning of matrimony). If you build a family, you will have children. You have to educate them with all right things, so that they can grow in the right way also as well. Your children are gift as you already built a family, so you have to really really care with the children since its a grace from God.

From my brief explanation, we can there is a sequence for having a matrimony. To marry someone is not easy, because it has a value to marry someone, and it has a commitment. You might have to sacrifice a lot of things for your wedding. But to marry means you open a new life, a new life with someone that you really love and you are ready to be faithful with. And also, it have to happen only once in a lifetime. So, you have to be careful with your choice, you have to know him/her very well, and you really have to make sure that your choice is the one that God sent to you.

Well, this is my short opinion regarding matrimony. Any ideas and suggestion are highly welcome :).

 
1 Comment

Posted by on May 16, 2011 in English, Katolik

 

Tomcat 7.0 for Beginners

tomcat

tomcat


Tomcat, or officially named Apache Tomcat is a light-weight web container used for deploying and running web application based on Java. Just like apache for PHP as container, tomcat’s role is becoming a runtime for java web application. There are so many web container in the world but i choose tomcat as this tutorial since tomcat is quite easy to be understood and the server management is not that difficult. So for beginner, tomcat is a good kickstart to a real application server. For development, tomcat is a best friend since it has a very quick startup and it’s reliable for small number of applications.

INSTALLING TOMCAT 7.0

1. Download your Tomcat 7.0

Download the latest tomcat 7.0 in here.
Note : I prefer to use the distribution version one, so i recommend to choose any files except the installer version for windows since it is easy to be modified and to be moved to other computer.

2. Extract the downloaded file

Extract the file, then you will see a structure like this :

Folder Structure

After you finished this steps, you have succesfully installed your tomcat to your computer. Now let’s heading on the configuration.

CONFIGURING TOMCAT

1. Define administrator password

In tomcat, administrator term is defined as manager. In default, there will be no user in tomcat 7.0 as a manager. You have to add yours. To add new user, go to ${TOMCAT_INSTALLATION_DIR}/conf/ and open tomcat-users.xml.

At the first time you will see line 29 to 35 will be commented. Please uncomment these lines by removing tag. After that, add additional line for creating your user, and the code will be seen something like this :

<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="role1" password="tomcat" roles="role1"/>
<user username="haka" password="haka" roles="manager-gui"/>

Note : Pay attention for the most bottom line. The username i set to “haka” and password set to “haka”. You can freely change these 2. But if you want the user to be manager, add manager-gui as the roles.

2. Configure local port

To configure any ports in Tomcat, go to ${TOMCAT_INSTALLATION_DIR}/conf/ and open file server.xml. After that, you can see whole configuration for server will be listed up there. For now, we will just customize port for host only. Go to line 67 in the file then you will see listing code like this :

You can change the port into any available port you like.
Note : If you have Oracle database installed, it might make a conflict since oracle listener use port 8080. So remember, if you have an oracle database installed, highly recommended that you change the port into other port, for example 8005, 8088, 8001, 8800,or whatever port you like ;). And also, you can change the connection timeout variable. This variable define how long will the system wait for starting the server. in this case, the value is 20000, means that the system will wait for 20 seconds IF the server is not tend to start.

I have oracle database installed in my current computer and i prefer port 8088, so that i change to port to 8088 :

<Connector port="8088" protocol="HTTP/1.1"
               connectionTimeout="20000" 
               redirectPort="8443" />

For a while, you have done with the minimum configuration for tomcat.

3. Starting the service

For starting the service, go to ${TOMCAT_INSTALLATION_DIR}/bin/ then execute file startup.bat. If everything is working fine, you will see a pop up uneditable command prompt windows like this :

Congratulations!! You have succesfully started your tomcat server :D

4. Accessing root directory in server

Go to your browser and type this :

http://localhost:8088/

The 8088 port is really depend on what port you set in the server.xml. If you use 8080, then you have to type localhost:8080, and so on. If it’s successful, then you will see display like this :

5. Administering your server

You have set your username and password for the manager. If you want to administer your server, go to http://localhost:8088/manager/html. Then a pop dialog will be prompted, requesting user name and password.

Enter your username and password (for my case, user is haka and password is haka). If it’s succesfull, the screen will drive you to the manager screen :

Tomcat Administration

You can customize your server, customize the application deployed and you can even deploy your web application via this screen.

That’s tutorial for beginners of Tomcat. Next time i will prepare the tutorial of how deploying your first java web application. Stay tune ;). God bless!

 
13 Comments

Posted by on October 1, 2010 in English, Programming

 

Tags: , , , , , ,

Review : iReport 3.7 book

This month, i received an email from Packt Publishing, and i’m offered to review their latest release book. It was a great opportunity for me since packtpub is a huge book publisher. Packtpub has just released their latest book about JasperReport. The name is iReport 3.7, written by Shamsuddin Ahammad.

PacktPub : iReport 3.7

PacktPub : iReport 3.7

I read this book and i can only say that, this book is what you are looking for to start learning about JasperReport until you mastering it. The book show you how to learn about JasperReport from scratch and step by step. You will not got lost in the middle of the book. You can find the style of reading in this book is very unique. Once again, i’m sure you will get interested in reading this book.

The book comprises of 12 chapters, and the order of all chapters is sorted by how you should understand iReport first until you got advanced. Every piece of definition, code snippet, and display highlight is explained very clear. You will not only understand but will totally understand about what is being explained. And of course, because this book is offered for ones who want to start learning JasperReport, all you need to have is only a passion to learn.

Chapter 1 : Introduction to iReport

This chapter provided all about beginning iReport, downloading and installing iReport, and so on. This chapter provide a very basic introduction of how using basic iReport.

Chapter 2 : Building Your First Report
In this chapter, the book provided about how to build your first report, creating datasource and exporting the report.

Chapter 3 : Report Layout and Formatting
This section explained about setting up your report pages and how to make your report professional look. This section also explained about positioning elements to your report.

Chapter 4 : Using Variables
This section is mainly discussed about variables, how to use and implement it into your report.

Chapter 5 : Using Parameters
In this chapter, the writer explains very clear about parameter, what is parameter in iReport and how to implement it in your report.

Chapter 6 : Grouping Data in Reports
You can group your data in iReport and this section provides how to do it in step by step.

Chapter 7 : Subreports
Subreport is an important element in a report and this section explains about creating your subreport and bind it to an existing report.

Chapter 8: Crosstab Report
In this chapter you will gain an understanding of what crosstab reports are and how to use crosstab reports.

Chapter 9: Charting
In this chapter you will learn how to create report with pie charts, 3d pie charts, and bar charts. Since charting is an important of report, you need to pay attention for this chapter.

Chapter 10: Working with Images
This chapter covers showing images in reports from the database, static images from the hard drive, and setting a background image in a report.

Chapter 11: Calling iReport from Java Applications
In this chapter you will learn about the JasperReports library for calling iReport from your Java application.

Chapter 12: iReport in NetBeans
This section covers about installing iReport plugins in NetBeans and creating reports from inside NetBeans IDE.

Chapter 13: A Sample Database
This chapter presents the design and development of an inventory.

Approach

Step-by-step example-based tutorials make is very easy to be learnt and be followed.

Who this book is written for

This book is a very good book and good for all JasperReports developer from beginner to advance.

I highly recommend this book for all beginners of iReport. For more information, please visit this link.

 
13 Comments

Posted by on April 4, 2010 in Uncategorized

 

New to JasperReport : Parameterizing your Report

In previous article, you’ve learnt how to build your first application using JasperReport. you see that the query fetch all record. We, somehow, never need all records but only several records. In SQL, we can use WHERE clause to add conditional for fetching records. We can do this too with JasperReport.

1. Open your iReport designer
If you follow the tutorial from scratch, open your recent report project about Employee Report. Now, add Parameter into your iReport by right-click to parameters node on the left :

Give it name PARAM_E_ID.

2. Integrate your parameter variable with the query
To integrate your parameter variable, type this query in your query window :

SELECT employee_id AS "E_ID", employee_name AS "E_NAME", salary AS "E_SALARY" FROM employees WHERE employee_id = $P{PARAM_E_ID}

Note : You can dynamically add value to your parameter variable.

3. Preview your report
Click preview button, then you’ll be prompted to insert a value to PARAM_E_ID parameter :

After that, you will see the report will be different :

Copy your .jasper file into your project. Replace it if it’s already exist.

4. Code your application
To fill your parameter as conditional from your Java Application to your report, use java.util.HashMap. In this case, we have 1 parameter, PARAM_E_ID. Then in your hashmap, use this code :

HashMap hm = new HashMap();
hm.put("PARAM_E_ID","E0001");
//and your other parameter

Let’s recall my previous article here and look at the java code part. You will see in the line 52 the code is like this :

JasperPrint jp = JasperFillManager.fillReport(is, null, conn);

To unite the hashmap with your report, replace this part into this :

HashMap hm = new HashMap();
hm.put("PARAM_E_ID","E0001");
JasperPrint jp = JasperFillManager.fillReport(is, hm, conn);

After that, you will see the difference :

Enjoy!

 
4 Comments

Posted by on March 1, 2010 in English, Programming

 

Tags: , , , , , , , ,

New to JasperReport : Build your first impressive application (part 2)

So now, you’ve seen the 2 previous articles. And now, let’s move on the core of JasperReport and the integration of it to the desktop application. I guarantee you that you really need this article because you don’t want your application only capable to do just System.out.println(“Hello Everybody!”); do you?

Let’s get it on!

1. Building your report
You can see in the right panel, there’s a palette panel. If you can’t see it, go to Window -> Palette to activate palette panel. Drag a static text to the Title Section as follows :

Make it look like this

After that, insert column title into similar like this :

Note : You can add additional line, text, etc as you like.

2. Integrate it with Query
Click on the button with this icon :
You will see a query window. Type this query on the text area (note that this is SQL query, not Hibernate query, JPQL, etc.)

SELECT employee_id AS "E_ID", employee_name AS "E_NAME", salary AS "E_SALARY" FROM employees

Let’s analyze the code above. I’m sure that all of you must be familiar with this code. But one thing you have to know that, in JasperReport, ALIAS will be converted automatically into FIELDS. In this case, you have 3 aliases, E_ID, E_NAME, and E_SALARY. All of these will be converted into JasperReport FIELDS Variable, so that you can place these elements in this design.

Next, place these 3 elements into your design (Dont forget, put these in Details Section), just simply like this :

3. Testing your report
Click on preview button in the toolbar. If you work in the right way, you will see display like this :

The report works fine. Remember, whenever you clicked on Preview, the iReport will automatically compile the report from .jrxml into .jasper. The .jasper file is the generated object that you can use it and directly integrate it with the application.

Note : for iReport 3.7.0 user, you have to change the default language from Groovy to Java. Right click on your report name node in the left side, choose properties, and change the language from Groovy to Java.

Let’s move on to Netbeans.

4. Create a new Java Application Project and Insert JasperReport library
Create the java application first. Uncheck the Create Main Class option. After that, add JasperReport library and MySQL JDBC Driver to your project (Right click on the library node of your project, add new library)as follow :

Add New Library

Add JasperReport library & MySQL JDBC Driver on it. You will see like this once you get done :

Next, create 2 package in your Source Packages, 1 package to place your report, the other one to place your main application. Give it name :

Move your .jasper file into your report package.

Insert a main class into your application package.

5. Code your application

Open your main class, and insert this code to your class (i will explain it component per component) :

package id.hans.employee.application;

import java.awt.Dimension;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.swing.JRViewer;

/**
 *
 * @author Hans Kristanto
 */
public class MainApplication {

    Connection conn = null;

    public void initConnection(){
       
        String HOST = "jdbc:mysql://localhost:3306/DATABASE_NAME";
        String USERNAME = "YOUR_MYSQL_USERNAME";
        String PASSWORD = "YOUR_MYSQL_PASSWORD";
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }

        try {
            conn = DriverManager.getConnection(HOST, USERNAME, PASSWORD);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public void showReport(){
        
        //Path to your .jasper file in your package
        String reportName = "id/hans/employee/report/EmployeeReport.jasper";
        
        //Get a stream to read the file
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(reportName);

        try {
	 //Fill the report with parameter, connection and the stream reader		
            JasperPrint jp = JasperFillManager.fillReport(is, null, conn);
	    
  	 //Viewer for JasperReport
            JRViewer jv = new JRViewer(jp);
	
	 //Insert viewer to a JFrame to make it showable
            JFrame jf = new JFrame();
            jf.getContentPane().add(jv);
            jf.validate();
            jf.setVisible(true);
            jf.setSize(new Dimension(800,600));
            jf.setLocation(300,100);
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        } catch (JRException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {

        MainApplication ma = new MainApplication();
        ma.initConnection();
        ma.showReport();
    }

}

If no problem occured, you will see display like this :

Your Report display. Cool isn't it?

Congratulations! you’ve created your first JasperReport application!

 
73 Comments

Posted by on March 1, 2010 in English, Programming

 

Tags: , , , , , , , ,

 
Follow

Get every new post delivered to your Inbox.