Tuesday, July 17, 2012

web.xml deployment descriptor for diffrent sevlet versions

today i am gong to discuss the different web.xml deployment descriptors available for each servlet API versions. hope this might be helpful for you to decide the correct web.xml DD definition base on the servlet API version you are using.

1. Servlet 2.3 Deployment Descriptor

For Servlet 2.3, using a dtd file to validate the XML content. Not recommend to use, consider upgrading to version 2.4 or 2.5.

P.S Maven 3′s quick start web app is still generating this

web.xml -> Namespace = none
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
 
<web-app>
  <display-name>Servlet 2.3 Web Application</display-name>
</web-app>
 
 

2. Servlet 2.4 deployment descriptor

For Servlet 2.4, using xsd to validate XML content, the most popular web.xml version.
web.xml -> Namespace = http://java.sun.com/xml/ns/j2ee
 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
       http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
       version="2.4">

  <display-name>Servlet 2.4 Web Application</display-name>
</web-app>
 
 

3. Servlet 2.5 deployment descriptor

For Servlet 2.5, using xsd to validate XML content, from this version and onward, the namespace is changed.

web.xml -> Namespace = http://java.sun.com/xml/ns/javaee
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
       version="2.5">

  <display-name>Servlet 2.5 Web Application</display-name>
</web-app>
 
 

4. Servlet 3.0 deployment descriptor

For Servlet 3.0, with xsd validation also, the latest version, but not many people using it.

web.xml -> Namespace = http://java.sun.com/xml/ns/javaee
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
       version="3.0">

  <display-name>Servlet 3.0 Web Application</display-name>
</web-app>
 
 
 
hope this will helpful for you !!!


Regards
Chathuranga Tennakoon
chathuranga.t@gmail.com

references 
http://www.mkyong.com/web-development/the-web-xml-deployment-descriptor-examples/

Tuesday, April 10, 2012

WSDL (Web Service Description Language) Binding in WebService

WSDL (Web Service Description Language ) describes the web service message format and the protocol details. WSDL style binding describes how the WSDL details are bounded to the web service.  There are two WSDL binding styles.

1. RPC (Remote Procedure Call) Style Binding
2. Document Style Binding

http://publib.boulder.ibm.com/infocenter/dmndhelp/v6rxmx/index.jsp?topic=/com.ibm.wbit.help.ui.doc/topics/rwsdlstyle.html

Thursday, April 5, 2012

how to change MySQL user password with console(MySQL console)

login to the MySQL  server with the console provided.

mysql  -uroot -p

then  change the database as mysql

use mysql;

then use the following command to change the root password


//the new password of the user whose password should be changed
update user set password=PASSWORD("abc123") where User='root';


Hope this will helpful for you!!!

Thanks and Regards
Chathuranga Tenakoon
chathuranga.t@gmail.com

Monday, April 2, 2012

Transefer PHP class instances as session data using serialization, compression and encryption techniques


The intension of this article is to explain how the PHP class instances(objects) are transferred among PHP pages with the use of sessions. All the objects (including contents) will be serialized, then compressed and encrypted prior to store in the user session.
When retrieving the object from the session variable, you need to remember that it is in the base64 decrypted format. Once you decrypt the object, you will get the object as a deflated string(compressed data). Then you need to inflate (decompress) the deflated string. Then you will get the serialized object(instance). Then you need to deserialized (unserialized) the instance to construct the original instance.

 please refer the below project structure.


we will go through each of the source code files as below.

ConfigData.php
<?php
/**
 * Created by
 * User: Chathuranga Tennakoon
 * Email: chathuranga.t@gmail.com
 * Blog: http://chathurangat.blogspot.com
 * Date: 03/29/12
 * Time: 9:13 AM
 * IDE:  JetBrains PhpStorm.
 */
class ConfigData
{

    private  $name;
    private  $email;
    private  $website;


    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setWebsite($website)
    {
        $this->website = $website;
    }

    public function getWebsite()
    {
        return $this->website;
    }

}

?>

TestInterface.php
<?php
/**
 * Created by
 * User: Chathuranga Tennakoon
 * Email: chathuranga.t@gmail.com
 * Blog: http://chathurangat.blogspot.com
 * Date: 03/29/12
 * Time: 9:13 AM
 * IDE:  JetBrains PhpStorm.
 */
interface TestInterface
{

public function getInstance();
public function setInstance(ConfigData $cfgData);

}
?>


TestImpl.php
<?php
/**
 * Created by
 * User: Chathuranga Tennakoon
 * Email: chathuranga.t@gmail.com
 * Blog: http://chathurangat.blogspot.com
 * Date: 03/29/12
 * Time: 9:13 AM
 * IDE:  JetBrains PhpStorm.
 */
include "interfaces/TestInterface.php";
include "config/ConfigData.php";


class TestImpl implements TestInterface
{
     private $config = NULL;

    public function getInstance()
    {

        return $this->config;
    }


    public function setInstance(ConfigData $cfgData){

        $this->config = $cfgData;
    }

}


?>


testSend.php
<?php
/**
 * Created by
 * User: Chathuranga Tennakoon
 * Email: chathuranga.t@gmail.com
 * Blog: http://chathurangat.blogspot.com
 * Date: 03/29/12
 * Time: 9:13 AM
 * IDE:  JetBrains PhpStorm.
 */
session_start();

include "classes/TestImpl.php";

$testImpl =  new TestImpl();

$config = new ConfigData();
$config->setName("chathuranga tennakoon");
$config->setEmail("chathuranga.t@gmail.com");
$config->setWebsite("http://chathurangat.blogspot.com");


$testImpl  = new TestImpl();
$testImpl->setInstance($config);

$_SESSION["TestImplObject"] = base64_encode(gzdeflate(serialize($testImpl)));

?>


testReceive.php
<?php

session_start();

include "classes/TestImpl.php";


$testImpl = new TestImpl();

//printing the session data as it is 
echo "<b>Session Data (Encrypted) </b>[".$_SESSION["TestImplObject"]."]<br/><br/>";

//decrypt the session data with base64 decryption mechanism
echo "<b>Decrypted Session Data in DEFLATE data format (Deflated Session Data) </b>[".base64_decode($_SESSION["TestImplObject"])."]<br/><br/>";

//inflating the deflated string
echo "<b>Inflated Value of the Deflated Value (Unserialized Object) </b>[".gzinflate(base64_decode($_SESSION["TestImplObject"]))."]<br/><br/>";

//unserializing the serialized object
echo "<b>Unserializing the Serialized Object (Serialized Object) </b>[".unserialize(gzinflate(base64_decode($_SESSION["TestImplObject"])))."]<br/><br/>";

//do all above operations in a single statement(line)
$testImpl = new TestImpl();
$testImpl = unserialize(gzinflate(base64_decode($_SESSION["TestImplObject"])));


echo "TestImpl Instance (Serialized Shared Instance) <br/>";

//getting the instance of class ConfigData
$configInstance =  new ConfigData();
$configInstance = $testImpl->getInstance();

//retrieving the object reference ID of the $configInstance
echo "Object Reference ID of the retrieved instance of ConfigData class [".spl_object_hash($configInstance)."] <br/> <br/> <br/>";

echo "<b>Retrieved Member variable data of the instance of ConfigData class</b> <br/><br/>";

echo " <b>Name </b>[".$configInstance->getName()."]<br/><br>";
echo " <b>Email </b>[".$configInstance->getEmail()."]<br/><br>";
echo " <b>Website </b>[".$configInstance->getWebsite()."]<br/><br>";

?>
 


output of the testReceive.php is as follows.




The sample application is available to be downloaded through the following link.

Download Source Code


 Hope this will be helpful for you !!!
 Thanks and Regards
 Chathuranga Tennakoon
 chathuranga.t@gmail.com

Friday, March 23, 2012

Encrypt MySQL data using AES techniques

the data will be encrypted and stored in the database for providing an additional level of security for the data. In MySQL AES(Advanced Encryption Standard) algorithm can be used to encrypt and decrypt the data being inserted and retrieved.

  •  AES_ENCRYPT(data,encryption_key) - the method that can be used to encrypt the data being inserted. 
        e.g:- AES_ENCRYPT('chathuranga','abc123');

  • AES_DECRYPT(encrypted_data,encryptyed_key) 


suppose you need to encrypt and store the username and email of the every user in the database. these encrypted values are stored in the database as binary strings. therefore you must give suitable data types for the columns in the table to accept and hold binary string inputs. therefore we must use varbinary instead of varchar. create the following table in the database.

create table user_table(
user_id int auto_increment primary key,
username varbinary(100),
email varbinary(100));
 

then insert following data into the table created. you can see that  am using AES_ENCRYPT function with cha123 as the key.


insert into user_table values('',AES_ENCRYPT('chathuranga','cha123'),AES_ENCRYPT('chathuranga.t@gmail.com','cha123'));



insert into user_table values('',AES_ENCRYPT('darshana','cha123'),AES_ENCRYPT('chathurangat@lankacom.net','cha123'));


you can see that the data has been stored in a encrypted format. see below screen dump.


 the result of the select query is displayed in the encrypted format. if you need to see the original values (decrypted values) you have to use the AES_DECRYPT function to decrypt the values stored.  the command is as follows.


select AES_DECRYPT(username,'cha123') As username_origianal , AES_DECRYPT(email,'cha123') As email_origianal from user_table;

refer the below screen shot.



 finally try out  the following select statement to understand how to use where clause with an encrypted columns.


select AES_DECRYPT(username,'cha123') As username_origianal , 
AES_DECRYPT(email,'cha123') As email_origianal 
from user_table 
where username = AES_ENCRYPT('chathuranga','cha123');



Hope this will helpful for you!!!

Thanks and Regards,
Chathuranga Tennakoon
chathuranga.t@gmail.com

Tuesday, March 20, 2012

Adapter Pattern


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


interface TargetNumberSorter{
   
   
    public int[] sortIntegerList(int[] arr);
   
   
}



class AdapterNumberSorter implements TargetNumberSorter{
   
   
    public int[] sortIntegerList(int[] arr){
       
       
        //convert array to List<Integer>
        List<Integer> arrList =  new ArrayList<Integer>();
        for(int i=0;i<arr.length;i++){
           
            arrList.add(arr[i]);
        }
 
        //sort List<Integer> with Adaptee
       
        AdapteeNumberSorter ans = new AdapteeNumberSorter();
        List<Integer> sortedList = ans.sortIntegerList(arrList);
       
        int sortedArr[] =new int[sortedList.size()];
       
        //convert List<Integer>
        for(int index=0; index<sortedList.size();index++){
           
            sortedArr[index] = sortedList.get(index);
        }
       
         return sortedArr;
       
    }
   
   
}






class AdapteeNumberSorter{
   
    public List<Integer> sortIntegerList(List<Integer> inputList){
       
       
        Collections.sort(inputList);
       
        return inputList;
    }
   
}





class ApplicationClient{
   
   
    public static void main(String[]args){
       
        int arr[]={45,10,1,46,98,22,30,8};
       
        System.out.println("array before sorting Data ");
       
        for(int i=0;i<arr.length;i++){
           
            System.out.println("index ["+i+"] = "+arr[i]);
        }
       
        System.out.println("array after sorting Data ");
       
       
        TargetNumberSorter tns =  new AdapterNumberSorter();
       
        int sortredArr[] = tns.sortIntegerList(arr);
       
       
        for(int i=0;i<sortredArr.length;i++){
           
            System.out.println("index ["+i+"] = "+sortredArr[i]);
        }
       
       
    }
}

Thursday, March 8, 2012

JasperReports with PHP

Today i am going to write this article on the use of JasperReports in PHP as a reporting tool. Here i have used IReport-4.5.0 IDE for designing the JasperReport Template (known as jrxml file).In addition, you require a PHP library(third party) that generates PDF reports from the given jrxml document. this library can be downloaded from the following Git Repository
https://github.com/chathurangat/PhpJasperLibrary

or else you can downloaded through following link


In order to design the template, please follow the steps given below.

1. load the IReport Designer tool
(executable file is available inside the bin directory)


2.after loading the IReport Tool,select new report template to start the report designing.
(File -> New)
then you will get a new window with a list of available report templates. select a template out of the available templates. in my case i have selected the Blank A4 template. please refer below.








then click the Launch Report Wizard to load the selected report template.



3. then give a Report Name and browse a Location where the report file (jrxml file) should be saved.  Please refer below.






4. then click on Next to proceed with next phase. please refer below.





 As you can see in the Screen-shot, you will be displayed a list of available data source connections that can be used in your report. if you wish to create a new data source connection, you are free to do so by clicking New button.


 5. if you click the New button to create new data source, you will be shown the below screen to select the the data source type. ( the data source type should be selected based on the application requirements. ) since this is PHP based web application, i have selected Database JDBC Connection as the data source type.



6. once you select the data source, click on next to proceed with next step. next will be the below screen.



here you have to provide the JDBC connection details.

 Name : just give any name for this connection for later reference  identification purpose


JDBC Driver:  select the most suitable JDBC driver from the given list based on your database. since i am using MySQL server database, i have selected  MySQL-JDBC Driver.


JDBC URL: make sure to edit the jdbc url based on your sever and database name. the default value of the jdbc url does not change, based on the value you provided for server and database. therefore please edit it manually.

Server Address : IP Address of the database sever. if the database is in your local machine, use localhost as IP.

Database : Database name that you are going to connect.


username: Username of the database server.

password : Password of the database server.


after filling all the configuration details, you can test the database conncetion by clicking the Test button provided. sometimes it may ask you to re-enter the database password. if the connection is successful, you will get a successful message as follows. then you can Save your new data source connection.





 7. then you can use your newly created data source for designing the query for your report. select the newly created data source and press Design Query button. then you will get the below window for designing the Query.


 
you will see a list of tables available in the connected database. you can Drag and Drop these tables to the provided area for designing the Query. then customize the columns displayed in the report by using the check boxes provided for each column.


8. once the Query is designed, press OK to finish it. the click Next to proceed with next phase. then next step is to select the required fields for your report out of the available all resulted columns of the Query you designed. add and remove the required database columns for your report with the provided button. please refer the below screen shot.




 9. after completing the above operation, you can press Next button for continue with next phase. next phase is for applying the Group By clause for the report view. then phase is optional and you can skip this step by clicking just Next button. then the initial process of the report design is finished and you will be notified with the below screen. jut click on finish button.



10. then it will load and display the created .jrxml file. you are required to remember that this is the file that contains your report template. you can design the report as you wish by providing preferable title, footer and other required fileds.


11. the designing utilities are available in the Report Inspector window. please refer below screen shot.


as you can see that the selected database column fields are available under the Fields. you can drag and drop the database fields in into the Detail1 Section of your Report.Once you drag a database field, its column header section will be automatically visible under Column Header section. In addition, the data field is visible under the Detail 1 Section. you can edit the column name as you wish.

12. Once the Design is done, you can preview the design using the Preview button. 


13. The Report design elements are available in the palette window. you can get the palette window Window -> Palette


14. Once all the design is done, the it is time to integrate with your PHP application. make sure to download and import the PhpJasperLibrary in your PHP script. (copy both .jasper and .jrxml files into a same directory and give the reference in the PHP script)


report_view.php

<?php

//Import the PhpJasperLibrary
include_once('PhpJasperLibrary/tcpdf/tcpdf.php');
include_once("PhpJasperLibrary/PHPJasperXML.inc.php");


//database connection details

$server="192.168.0.11";
$db="lcs_ims";
$user="web";
$pass="abc123@#";
$version="0.8b";
$pgport=5432;
$pchartfolder="./class/pchart2";


//display errors should be off in the php.ini file
ini_set('display_errors', 0);

//setting the path to the created jrxml file
$xml =  simplexml_load_file("report/chathuReport.jrxml");

$PHPJasperXML = new PHPJasperXML();
//$PHPJasperXML->debugsql=true;
//$PHPJasperXML->arrayParameter=array("parameter1"=>1);
$PHPJasperXML->xml_dismantle($xml);

$PHPJasperXML->transferDBtoArray($server,$user,$pass,$db);
$PHPJasperXML->outpage("I");    //page output method I:standard output  D:Download file


?>



access the report_view.php file in your LAMP/WAMP server. yo will get the report in PDF format.



Hope this will helpful for you!

Thanks and Regards,
Chathuranga Tennakoon
chathuranga.t@gmail.com



Sunday, March 4, 2012

Cron Job example with PHP and Linux

today i am going to show you a practical example about cron job in linux environment. i extremely believe that you know what is a cron job and what is the purpose of using a crone job. if you dont know just google and get a proper understanding before proceeding with this article.

here i have assumed that you have successfully installed LAMP server in your PC and php projects are running without having any issue. today i am going to show you how to run Cron job in linux that executes the executes the php script in every 1 minute. the php script will insert a record to the given database table at each execution.

1. first set up the database and the table as follows.
/* create the database */
create database cron_job_example;

/* use the database */
use cron_job_example;

/* create the table */
create table cron_job_data(
id int,
name varchar(100),
date_time varchar(100));



2. set up the Php Script in the www directory of your LAMP server as follows.

in my case, it is located at /var/www and create a directory called sample_site

then copy the following Php file to the sample_site directory.

sample.php

<?php

//database connection details

$db_server="localhost";
$db_username="root";
$db_password="abc123@#";
$db_name="cron_job_example";

$con = mysql_connect($db_server,$db_username,$db_password);

if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db($db_name, $con);

$date = date("Y-m-d");

mysql_query("INSERT INTO cron_job_data (id, name,date_time)
VALUES (1, 'chathuranga','".$date."')");

?>


3. then use Linux terminal to create the cron job file to achieve the target.

you can use any of preferred text editor (vi, gedit etc...)  to create cron file. use following syntax. i have used gedit text editor for this example.

gedit  name_for_file.cron  (it is importnat that you must use .cron extension with the file name)

in my case,

gedit chathuranga.cron


then add the following entry in the newly opened file.

*/1 * * * *  wget http://localhost/cron_job/cron_job_file.php


general syntax of the above entry
<time_specified>  <command>

<time_specified> - */1 * * * *
<command> - wget http://localhost/cron_job/cron_job_file.php

 more description as follows ......

* * * * * command to be executed
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59) 


then save the file and use following command in the Linux terminal to execute the cron job you created. (it is good if you can give the full permission(777) for your cron job file before doing following operation)

crontab chathuranga.cron


now your cron job will execute from hereafter.

ps: just google to find more on cronetab commands ;)



hope this will helpful for you!

cheers!!!
Chathuranga Tennakoon
chathuranga.t@gmail.com
chathurangat.blogspot.com




Tuesday, February 21, 2012

Hibernate Vs JPA

 i found a very good article that describes about JPA vs Hibernate. i decided to re-post that article in my blog for to improve the availability of the article. (even if the original source is not available, you can refer the article through my blog.)


JPA vs Hibernate 


Almost all of enterprise applications are required to access relational databases regularly. But a problem faced with earlier technologies (such as JDBC) was the impedance mismatch (difference between object-oriented and relational technologies). A solution for this problem was introduced through the introduction of an abstract layer called Persistence layer, which encapsulates database access from the business logic. JPA (Java Persistence API) is a framework dedicated for the management of relational data (using the persistence layer) in Java applications. There are many vendor implementations of JPA used within the Java developer community. Hibernate is the most popular such implementation of JPA (DataNucleus, EclipseLink and OpenJPA are some others). The newest JPA version (JPA 2.0) is fully supported by Hibernate 3.5, which was released in March, 2010.

What is JPA?

JPA is a framework for managing relational data for Java. It can be used with applications utilizing JSE (Java Platform, Standard Edition) or JEE (Java Platform, Enterprise Edition). Its current version is JPA 2.0, which was released on 10 Dec, 2009. JPA replaced EJB 2.0 and EJB 1.1 entity beans (which were heavily criticized for being heavyweight by the Java developer community). Although entity beans (in EJB) provided persistence objects, many developers were used to utilizing relatively lightweight objects offered by DAO (Data Access Objects) and other similar frameworks instead. As a result, JPA was introduced, and it captured many of the neat features of the frameworks mentioned above.
Persistence as described in JPA covers the API (defined in javax.persistence), JPQL (Java Platform, Enterprise Edition) and metadata required for relational objects. State of a persistence entity is typically persisted in to a table. Instances of an entity correspond to rows of the table of the relational database. Metadata is used to express the relationships between entities. Annotations or separate XML descriptor files (deployed with the application) are used to specify metadata in entity classes. JPQL, which is similar to SQL queries, are used to query stored entities.

What is Hibernate?

Hibernate is a framework that can be used for object-relational mapping intended for Java programming language. More specifically, it is an ORM (object-relational mapping) library that can be used to map object-relational model in to conventional relational model. In simple terms, it creates a mapping between Java classes and tables in relational databases, also between Java to SQL data types. Hibernate can also be used for data querying and retrieving by generating SQL calls. Therefore, the programmer is relieved from the manual handling of result sets and converting objects. Hibernate is released as a free and open source framework distributed under GNU license. An implementation for JPA API is provided in Hibernate 3.2 and later versions. Gavin King is the founder of Hibernate.

What is the difference between JPA and Hibernate?

JPA is a framework for managing relational data in Java applications, while Hibernate is a specific implementation of JPA (so ideally, JPA and Hibernate cannot be directly compared). In other words, Hibernate is one of the most popular frameworks that implements JPA. Hibernate implements JPA through Hibernate Annotation and EntityManager libraries that are implemented on top of Hibernate Core libraries. Both EntityManager and Annotations follow the lifecycle of Hibernate. The newest JPA version (JPA 2.0) is fully supported by Hibernate 3.5. JPA has the benefit of having an interface that is standardized, so the developer community will be more familiar with it than Hibernate. On the other hand, native Hibernate APIs can be considered more powerful because its features are a superset of that of JPA.

source :- http://www.differencebetween.com/difference-between-jpa-and-vs-hibernate/

Thanks and Credits should go to the Original Author who compose this valuable article.

cheers!!!
Chathuranga Tennakoon
chathuranga.t@gmail.com

Monday, February 20, 2012

Spring Security - User Authentication with UserDetailService

http://stackoverflow.com/questions/4489703/how-to-use-spring-security-with-jpa

Create your own HTTP 403 Access Denied Page in Spring Security

http://www.mkyong.com/spring-security/customize-http-403-access-denied-page-in-spring-security/

http://krams915.blogspot.com/2010/12/spring-security-mvc-integration_18.html

Friday, February 17, 2012

Many to Many mapping in JPA annotations

ER diagram
------





Student.java
package org.convey.user.registration.model;

import javax.persistence.*;
import java.util.List;

/**
 * Name: Chathuranga Tennakoon
 * Mobile: 0094759610139
 * Blog: chathurangat.blogspot.com
 * Email: chathuranga.t@gmail.com
 */
@Entity
@Table(name="student")
public class Student {

    @Id
    @GeneratedValue
    @Column(name = "student_id")
    private int studentId;

    @Column(name="student_name")
    private String studentName;

    @Column(name="student_address")
    private String studentAddress;

    @Column(name="version")
    private long version;

    @ManyToMany
    @JoinTable(
            name="student_course",
            joinColumns = {@JoinColumn(name = "studentID",referencedColumnName = "student_id")},
            inverseJoinColumns = {@JoinColumn(name = "courseID", referencedColumnName = "course_id")})
    private List courses;


    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getStudentAddress() {
        return studentAddress;
    }

    public void setStudentAddress(String studentAddress) {
        this.studentAddress = studentAddress;
    }

    public long getVersion() {
        return version;
    }

    public void setVersion(long version) {
        this.version = version;
    }

    public List getCourses() {
        return courses;
    }

    public void setCourses(List courses) {
        this.courses = courses;
    }
}



Course.java

package org.convey.user.registration.model;

import javax.persistence.*;
import java.util.List;

/**
 * Name: Chathuranga Tennakoon
 * Mobile: 0094759610139
 * Blog: chathurangat.blogspot.com
 * Email: chathuranga.t@gmail.com
 */
@Entity
@Table(name="course")
public class Course {

    @Id
    @GeneratedValue
    @Column(name="course_id")
    private int courseId;

    @Column(name="course_name")
    private String courseName;


    @Column(name="course_description")
    private String courseDescription;

    @Column(name="version")
    private long version;

    @ManyToMany
    @JoinTable(
            name="student_course",
            joinColumns = {@JoinColumn(name = "courseID",referencedColumnName = "course_id")},
            inverseJoinColumns = {@JoinColumn(name = "studentID", referencedColumnName = "student_id")})
    private List<Student>  students;


    public int getCourseId() {
        return courseId;
    }

    public void setCourseId(int courseId) {
        this.courseId = courseId;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public String getCourseDescription() {
        return courseDescription;
    }

    public void setCourseDescription(String courseDescription) {
        this.courseDescription = courseDescription;
    }

    public long getVersion() {
        return version;
    }

    public void setVersion(long version) {
        this.version = version;
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

}//course


  • Student can register for many courses.
  • A given course has many registered students
therefore many to many relationship exists between these two entities.therefore @ManyToMany Annotation is used to map the relationship between these two entities.

@JoinTable annotation is declared in the POJO class that owns the relationship. since this is many to many relationship, both class own the relationship. therefore @JoinTable annoatation is declared in the both classes. (therefore referential integrity constraint will be accurately maintained)

hope this will helpful for you!

 

Thursday, February 16, 2012

persist() vs merge() in Hibernate JPA

http://blog.xebia.com/2009/03/23/jpa-implementation-patterns-saving-detached-entities/

http://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge

Wednesday, February 15, 2012

JasperReport with Spring MVC (fully working example with source code and explanation)

Today i am going to discuss how to integrate  jasper report with Spring MVC. i will be using following sample Spring MVC Application to show how the spring mvc and jasper report is integrated. you can download this application through following URL or GitHub repository.

https://github.com/chathurangat/spring-mvc-jpa-example

or

4shared URL

once you download the project, load it with your preferable development IDE. i have use Intelli J IDEA. the project structure is shown in the below screen shot.



the jasper report will be designed to display a list of Users who are already in the database(in User Table). this User table has been mapped to the User.java model that is available inside the org.convey.user.registration.model package. you can see the source code of the User.java model as follows.

User.java

package org.convey.user.registration.model;

import javax.persistence.*;
import java.util.Date;
import java.util.List;


@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id")
    private int id;

    @Column(name = "username" , nullable = false , unique = true)
    private String userName;

    @Column(name = "password" , nullable = false)
    private String passWord;

    @Column(name = "email" , nullable = false , unique = true)
    private String email;

    @Column(name = "confirmation_code",length = 20)
    private String confirmationCode;

    @Column(name = "first_name" , length = 50,nullable = false)
    private String firstName;

    @Column(name = "last_name" , length = 50)
    private String lastName;

    @Column(name = "register_date")
    private Date registeredDate;

    @Column(name = "activate_status")
    private boolean  activate;

    @Version
    private int version;

    @ManyToMany
    @JoinTable(name ="user_module",
            joinColumns = {@JoinColumn(name = "userID", referencedColumnName = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "moduleID", referencedColumnName ="module_id")})
    private List<Module> modules;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getConfirmationCode() {
        return confirmationCode;
    }

    public void setConfirmationCode(String confirmationCode) {
        this.confirmationCode = confirmationCode;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Date getRegisteredDate() {
        return registeredDate;
    }

    public void setRegisteredDate(Date registeredDate) {
        this.registeredDate = registeredDate;
    }

    public boolean isActivate() {
        return activate;
    }

    public void setActivate(boolean activate) {
        this.activate = activate;
    }


    public List<Module> getModules() {
        return modules;
    }

    public void setModules(List<Module> modules) {
        this.modules = modules;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

}//User




now it is the time to design the report using iReport. you can follow the below instructions to design your jasper report with iReport designer.

  • run the iReport tool. then File->New . then you will get the following set of available jasper report templates


  • In my case i have selected the Blank A4 report template. once you select the required report template, click Open this Template button to open the template.then you will get the following window.


then give a name for the report and select a location where the jrxml file should be saved.then click Next . after finishing all required operations you can see the selected template is loaded and ready o start the designing. please see the below.




if the palette is not automatically loaded in your designer, you can load it manually(window->palette)


you will see an another window called Report Inspector. you can add  the required fields for the report through this window. this can be done as follows.


right click on the Fields and select Add new Field Option.then you can see that newly added field is available under the Fields. you can change its attributes (name,type etc...) through the properties window. (Add up to four new fields)

Important:

when naming the fields, please make sure to name each field that is exactly same as the attribute name. In addition the data type (Field class) should also be same as the data type of identical attribute in the class. for more details, please see the below window. (we are going to design the report based on only the four attributes of the User class. therefore we need to create only four fields for the report). make sure to change the necessary properties of the newly added fields to reflect the below values.

attribute name(User class)     Field Name      Data Type(User class)     Field Class
 id                                              id                    int                                      Integer
 userName                                userName       String                                 String
 email                                        email               String                                 String
 firstName                                firstName        String                                 String


you can see that both attribute names and field names are identical. in addition there data types are also identical.now i assume that you have added new fields and changed their names and data types to meet above requirements. you can see all newly added fields as follows.



now you have loaded required components for your report design. now you can start  the design of your report. i will show you how to added newly created fields for your report.


drag and drop the newly added fields to the Detail 1 section of your report. please refer the below screen shot.



you can preview the design with the preview button.

now it is the time to start the jasper report integration with the spring mvc web application.suppose you have already downloaded the sample application given above for proceeding with this tutorial. you need to place the created jrxml file  in the class path. (in my case chathuranga-test-report.jrxml ).

 the jrxml file should be placed in the spring-mvc-jpa-jasper-report-example/src/main/resources location of the above downloaded project.

 then follow the instructions given below.

1. add the following maven dependencies to the pom.xml file.


<dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>3.7.6</version>
            <type>jar</type>
            <scope>compile</scope>           
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.6</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>2.1</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>1.7.0</version>
        </dependency> 
 
 
2. add the following Report controller to your controller package.
(available in spring-mvc-jpa-jasper-report-example/src/main/java/org/convey/user/registration/controller )

ReportController.java

package org.convey.user.registration.controller;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.convey.user.registration.dao.UserDao;
import org.convey.user.registration.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Controller
@RequestMapping("/report/")
public class ReportController {


    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserDao userDao;

    @RequestMapping(method = RequestMethod.GET , value = "pdf")
    public ModelAndView generatePdfReport(ModelAndView modelAndView){

        logger.debug("--------------generate PDF report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //pdfReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("pdfReport", parameterMap);

        return modelAndView;

    }//generatePdfReport



    @RequestMapping(method = RequestMethod.GET , value = "xls")
    public ModelAndView generateXlsReport(ModelAndView modelAndView){

        logger.debug("--------------generate XLS report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //xlsReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("xlsReport", parameterMap);

        return modelAndView;

    }//generatePdfReport


    @RequestMapping(method = RequestMethod.GET , value = "csv")
    public ModelAndView generateCsvReport(ModelAndView modelAndView){

        logger.debug("--------------generate CSV report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //xlsReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("csvReport", parameterMap);

        return modelAndView;

    }//generatePdfReport



    @RequestMapping(method = RequestMethod.GET , value = "html")
    public ModelAndView generateHtmlReport(ModelAndView modelAndView){

        logger.debug("--------------generate HTML report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //xlsReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("htmlReport", parameterMap);

        return modelAndView;

    }//generatePdfReport


}//ReportController





3. add the following jasper-view.xml file to the same directory where the applicationContext.xml file contains. (in this example, it is should be placed under the spring-mvc-jpa-jasper-report-example/src/main/webapp/WEB-INF/spring/app directory.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/util 
  http://www.springframework.org/schema/util/spring-util-3.0.xsd">

     <!--here all the url value should contains the valid path for the jrxml file-->
    
    <bean id="pdfReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource" />


    <bean id="xlsReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsXlsView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource" />


    <bean id="htmlReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsHtmlView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource" />


    <bean id="csvReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsCsvView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource"/>


</beans>

here all the url properties should contains the valid reference for a jrxml file that should be used as the report template.


4. then make the below XmlViewResolver bean declaration in your  applicationContext.xml file

    <beans:bean class="org.springframework.web.servlet.view.XmlViewResolver">
        <beans:property name="location" value="/WEB-INF/spring/app/jasper-views.xml"/>
        <beans:property name="order" value="0"/>
    </beans:bean>  

the value of location property should contains the reference for the xml file where the jasper view declarations are available.(in this case jasper-view.xml)


In addition, import the jasper-view.xml file to your applicationContext.xml file by placing the below import statement in your applicationContext.xml 


<beans:import resource="jasper-views.xml"/> 

Please make sure to change your database properties in the spring-mvc-jpa-jasper-report-example/src/main/resources/db.properties file.

then build your project with maven and deploy it in the tomcat server. then use following urls for getting the report you need.

PDF Report
 http://localhost:8080/common-user-registration/spring/report/pdf

XLS Report
 http://localhost:8080/common-user-registration/spring/report/xls

CSV Report
 http://localhost:8080/common-user-registration/spring/report/csv

HTML Report
 http://localhost:8080/common-user-registration/spring/report/html


you can download the fully example of this application through the  following git repository .

https://github.com/chathurangat/spring-mvc-jpa-jasper-report-example

Hope this will helpful for you !!!

Regards
Chathuranga Tennakoon
chathuranga.t@gmail.com

Wednesday, January 11, 2012

Read Gmail Inbox using IMAP


There are two input fields in the below form. they are available to capture your gmail username(fully email) and password. Once you provide your username and password, just click login button tosend request to the imapEmail.php file.

loginForm.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>

<form method="post" name="login_form" id="login_form" action="imapEmail.php">


    Email <input type="text" name="email" id="email"/> <br/>
    Password <input type="password" name="password" id="password"/>

    <input type="submit" name="login" id="login" value="login" />

</form>

</body>
</html>



The below file will receive the Gmail username (email)  and password send by the loginForm.html page. then it will make necessary connection with the Gmail server to make the IMAP functionality work.

imapEmail.php
<?php

/*
Author:Chathuranga Tennakoon
Email: chathuranga.t@gmail.com
Web : http://chathurangat.blogspot.com
*/

/*check whether the request is POST*/
if(isset($_POST)){

    /* connect to gmail */
    $hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
    /* getting the username */
    $username = $_POST['email'];
    /*getting the password */
    $password = $_POST['password'];

    /* try to connect */
    $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

    /* grab emails */
    $emails = imap_search($inbox,'ALL');

    /* if emails are returned, cycle through each... */
    if($emails) {

        /* begin output var */
        $output = '';

        /* put the newest emails on top */
        rsort($emails);

        /* for every email... */
        foreach($emails as $email_number) {

            /* get information specific to this email */
            $overview = imap_fetch_overview($inbox,$email_number,0);
            $message = imap_fetchbody($inbox,$email_number,2);

            /* output the email header information */
            $output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">';
            $output.= '<span class="subject">'.$overview[0]->subject.'</span> ';
            $output.= '<span class="from">'.$overview[0]->from.'</span>';
            $output.= '<span class="date">on '.$overview[0]->date.'</span>';
            $output.= '</div>';

            /* output the email body */
            $output.= '<div class="body">'.$message.'</div>';
        }

        echo $output;
    }

    /* close the connection */
    imap_close($inbox);

}//if post request comes

?>



hepe this will helpful for you !

regards
Chathuranga Tennakoon
chathuranga.t@gmail.com