RSS

Category Archives: Programming

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: , , , ,

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: , , , , , ,

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: , , , , , , , ,

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

I’ve made a previous article about setting up your environment to be a “JasperReport-ready”. You can click here to recall it.

And now, in this article, i will guide you to build your first JasperReport application. For this part, i will split this tutorial into 2 parts.

1. Let’s setup a dummy database. I’m using MySQL 5.0. Suppose we have a database named db_jasper

CREATE TABLE employees (
    employee_id VARCHAR(6) NOT NULL PRIMARY KEY,
    employee_name VARCHAR(30),
    salary INT(6)
);

INSERT INTO employees VALUES ('E0001','Hans Kristanto',5000000);
INSERT INTO employees VALUES ('E0002','Conrad Alvin',3500000);
INSERT INTO employees VALUES ('E0003','Luna Hu',4500000);
INSERT INTO employees VALUES ('E0004','Jina Seo',3650000);
INSERT INTO employees VALUES ('E0005','Ivan Lu',4510000);
INSERT INTO employees VALUES ('E0006','Dennis Ewing',500000);

2. Start your iReport designer.

iReport designer main window

3. Create a new report template
Click on File -> New, then choose any template paper. For example, Blank A4 (in iReport 3.7.0). For iReport 3.7.0 below, just follow the wizard as usual.
NOTES : For a while, never use Report Wizard! You have to do it manually.
Give it name and directory to be saved. Click on finish.

New Report

4. After that, you will see window like this

Report Designer

If you to the report designer, there are 7 sections. I will explain it one by one :

  • Title : is section for placing title document. Title document will only appear on the first page of document.
  • Page Header : is section for placing page header, for example, page number, title, etc. This header will appear in every page of report but not in the first page.
  • Column Header : is section for placing column header for detail title, for example, Employee Name, Salary. You will see the different in the real application.
  • Details : is section where you place all data. Detail section will iterate as much as fetched data. Again, you will see how it works in the real application.
  • Column Footer : similar with Column Header, but placed in the foot.
  • Page Footer : similar with Page Header, but placed in the foot.
  • Summary : is section where you put all summarize. For example, summary of total employees, total profits/loss, etc.

You have to understand these 7 sections first before we continue to the next step. Already understand? let’s go ahead!

5. Create a datasource
in the toolbar, you will see an database icon with a plug in front of it. . You will see a new window appear :

Click on New button on the right side, then follow the wizard. My suggestion :
– use Database JDBC Connection.
– give it name afterward.
– use com.mysql.jdbc.Driver as the JDBC Driver.
– type your database name on JDBC URL e.g. : jdbc:mysql://localhost/db_jasper
– type your username and password.

After that, you will see the drop down next to the database icon will be set into our new datasource :

New DataSource

Everything is done for setting up. Let’s continue for the next core tutorial on the part 2.

 
56 Comments

Posted by on February 27, 2010 in English, Programming

 

Tags: , , , , , , , ,

New to JasperReport : Make it one for all and all for one

Reporting is a critical element that almost every application, either it’s desktop or web based should have. Almost all application developer focused on how to make strong reliable application, but they somewhat forget about this section. Today i will make a basic tutorial for an application that could be integrated into reporting engine, in this case, i will use JasperReport + Java.

Before we start to the core of this tutorial, i will show you how to make your PC/Laptop a “JasperReport-Ready”. Things that you should have to prepare :

1. Netbeans IDE
Netbeans is an integrated development environment (IDE) for Java, PHP, C/C++, Ruby, Python. You can download the latest release here

2. iReport Designer
iReport is a JasperReport designer. With this, you can build your preferable report, design it as your favourite, and integrate it into database. you can download the latest release here

3. JasperReport library
JasperReport is the core engine of reporting library. You can download the library here (need authentication). The dependencies libraries are :

After you’ve done downloaded such many things, let’s make your PC “JasperReport-ready”. Follow these steps :

1. Install Netbeans IDE latest version
2. Install iReport designer
3. Once you’ve installed these 2, follow these special steps :

  • Open your netbeans IDE
  • Click Tools->Libraries as follows :
  • nb-library

    Netbeans IDE

  • A new Library Manager window will appear. Click on New Library.. button
  • Type JasperReport on Library Name (you can use any other name as you like) :

    new-lib

    New Library

  • After that, you will back to Library Manager window. Choose your new jasper report library on Libraries list. Click on Add Jar/Folder button on the right side. Add JasperReport library and all dependencies library. Once it done, you will see a window like this :

    Library Manager

  • Click OK, then your IDE is ready for JasperReport development!

Have Fun!

continue to the next step

 
9 Comments

Posted by on February 27, 2010 in English, Programming

 

Tags: , , , , , , , ,

 
Follow

Get every new post delivered to your Inbox.