Saturday, November 30, 2013

Some Interesting gradle commands.

once the gradle is installed, now it is time to explore the functionalities of the gradle.


1. generating new java project with gradle.

   it is possible to generate simple java project with maven as follows.
 
   maven
   mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart

  the gradle also supported to generate project as follows.

  gradle
  gradle init --type java-library


2. converting the maven project to gradle.

it is possible to convert the maven project to gradle without any problem. it will create the build.gradle file and declare all the dependencies and other plugins declared in the pom.xml into the build.gradle file. In order to convert the maven project to gradle, you need to execute the following command  from the same directory of the project where the pom.xml file is located.

 gradle init



Hope this will helpful for you!

Thanks
Chathuranga Tennakoon
chathuranga.t@gmail.com
http://www.chathurangaonline.com







Thursday, November 28, 2013

How to install Gradle on Linux (Ubuntu)

if you dont know gradle, please go though the following website to get an understanding about gradle.

Gradle project home page :- http://www.gradle.org


follow the steps give below to install the gradle on your develop environment. (Linux based)

1. download the gradle distribution from the gradle website.

    http://www.gradle.org/downloads


2. extract the downloaded gradle distribution in any directory in your PC.

 
3. then add the GRADLE_HOME environmental variable. to add the environmental variable, follow the below instructions.

    3.1 sudo  gedit .bashrc
 
    3.2  add the following to the bottom of the .bashrc file

    GRADLE_HOME=<path to gradle bin file>  (e.g. /opt/gradle/gradle-1.5/bin )
    export GRADLE_HOME
    PATH=$PATH:$GRADLE_HOME
    export PATH
  
    3.2  source .bashrc



4. once the above changes are done, run gradle in the terminal to check whether gradle is properly installed.




Thanks
Chathuranga Tennakoon
chathuranga.t@gmail.com
http://www.chathurangaonline.com


 

Sunday, November 10, 2013

How to configure Tomcat to support SSL or https

first you need to create a keystore with following command.

 keytool -genkey -keyalg RSA -keystore /home/chathuranga/test_chathu.keystore

then answers for the questions that prompts sequentially. once the keystore is created, you can use the following command to check whether your keystore is there.

keytool -list -keystore /home/chathuranga/test_chathu.keystore


Now it is the time to do the tocat SSL configuration.

In tomcatHome/conf/server.xml file, change the SSL configuration as follows.

 <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"
           keystoreFile="/home/chathuranga/test_chathu.keystore"
           keystorePass="password" />


Then restart the tomcat server and try to access the following URL.

https://locahost:8443


you will notice that, your tomcat installation supports SSL(HTTPS) now.


Thanks
Chathuranga Tennakoon
chathuranga.t@gmail.com

Saturday, November 2, 2013

Application Authentication for JAX-WS web services

 the fully source code for this example can be found at  following gitHub repository.

Download code From GitHub

clone the project from gitHub and use the maven to build the project.
then deploy the web service in the tomcat server. (just copy the war file and i have already done the required web.xml and sun-haxws.xml configurations.)

if you want  to know, how to deploy the web service in tomcat, you can refer my previous blog post here

once the web service is deployed, you can run the web service client to test the web service and see how it works.


In application authentication, then authentication logic will be implemented there in the web service. therefore the web service will be responsible for handling the user authentication.

the web service client will send the user credentials (username and password) to the web service. please refer the following WebService Client.


package com.chathurangaonline.jaxws.samples.client;

import com.chathurangaonline.jaxws.samples.impl.*;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.MessageContext;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class WebServiceClientImpl {

    public static void main(String [] args){

        CalculatorServiceImplService calculatorServiceImplService = new CalculatorServiceImplService();
        CalculatorServiceImpl calculatorService = calculatorServiceImplService.getCalculatorServiceImplPort();

        Map<String, Object> req_ctx = ((BindingProvider)calculatorService).getRequestContext();
        Map<String, List<String>> headers = new HashMap<String, List<String>>();

        //setting up the username and password 
        headers.put("Username", Collections.singletonList("chathuranga"));
        headers.put("Password", Collections.singletonList("chathu@123"));
        req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);

        //in order to invoke the add method, you need to have valid login credentials
        double answer =  calculatorService.add(45,10);
        System.out.println(" answer is ["+answer+"]");
    }
}


The web service will extract the user login credentials (username and password) from the HTTP Request Headers and  will perform the user authentication.
(here we have hard coded the username and password for the demostration purpose and to make it more simple. in the production mode, you need to move then  database) 
 if the user authentication is successful, he will be able to access the web service. otherwise it will throw a HttpException as implemented.  refer the following web service implementation.


package com.chathurangaonline.jaxws.samples.impl;

import com.chathurangaonline.jaxws.samples.CalculatorService;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.http.HTTPException;
import java.util.List;
import java.util.Map;


@WebService
public class CalculatorServiceImpl implements CalculatorService{

    @Resource
    private WebServiceContext webServiceContext;

    @Override
    public double add(double num1, double num2) {
        //todo username and password was hardcoded only for the demonstration purpose. this should be configured to look up from database or somewhere else
        if(isAuthenticated("chathuranga","chathu@123")){
            //allowing the operation for the authenticated user
            return num1 + num2;
        }
        else{
            //non-authenticated user.
            throw  new HTTPException(401);
        }
    }

    @Override
    public double multiply(double num1, double num2) {
        return num1 * num2;
    }


    /**
     * <p>
     *     method for checking the application level authentication using the username and password provided.
     * </p>
     * @param username - username provided as {@link java.lang.String}
     * @param password - password provided as {@link java.lang.String}
     * @return {@link java.lang.Boolean} (true if user authenticated, otherwise false)
     */
    private boolean isAuthenticated(String username, String password){
        if(username!=null && password!=null){
            MessageContext messageContext = webServiceContext.getMessageContext();
            Map httpHeaders  = (Map) messageContext.get(MessageContext.HTTP_REQUEST_HEADERS);

            List usernameList  = (List) httpHeaders.get("username");
            List passwordList = (List) httpHeaders.get("password");

            if((usernameList!=null && usernameList.contains(username)) && (passwordList!=null && passwordList.contains(password))){
                return true;
            }
        }
        return false;
    }
}


The main problem with Application Authentication is the mix of security logic with the business logic might mess the code. it add some unnecessary complexity for the code with tight coupling. as a solution for this, we can go for the Container Managed Authentication and that will be my next blog post ;)

Thanks
Chathuranga Tennakoon
chathuranga.t@gmail.com

Saturday, October 5, 2013

One To Many Mapping example (Hibernate/JPA) annotations

Look at the following ER diagram.



by looking at the ER diagram, we can find the following relationship between two entities.

1. Lecturer can teach many courses
2. A course can be taught by only one lecturer


there are two possible ways to map the relationship between these two entities.

1. Mapping as One - To - Many Bidirectional Relationship
  
In this way, we maintain the mapping  in both entities. since the relationship is maintained in both side, it is possible to navigate to both directions.

Lecturer.java

package com.chathurangaonline.examples.model;

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

@Entity
@Table(name = "Lecturer")
public class Lecturer implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String lecName;

    @OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.PERSIST,mappedBy = "lecturer")
    private List<Course> courseList;

    public Long getId() {
        return id;
    }

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

    public List<Course> getCourseList() {
        return courseList;
    }

    public void setCourseList(List<Course> courseList) {
        this.courseList = courseList;
    }

    public String getLecName() {
        return lecName;
    }

    public void setLecName(String lecName) {
        this.lecName = lecName;
    }
}




Course.java

package com.chathurangaonline.examples.model;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "Course")
public class Course implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

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

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "lecturer_id")
    private Lecturer lecturer;

    public Long getId() {
        return id;
    }

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

    public String getCourseName() {
        return courseName;
    }

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

    public Lecturer getLecturer() {
        return lecturer;
    }

    public void setLecturer(Lecturer lecturer) {
        this.lecturer = lecturer;
    }
}


   

2 . Mapping as One - To - Many Unidirectional relationship

In this way, we do not maintain the mapping in both entities, we only maintain the mapping relationship in the owner entity.

Here the owner entity of the relationship is Course. therefore we maintain only the relationship from Course to Lecturer. on the other hand, Lecturer to Course relationship is not maintained.


Lecturer.java

package com.chathurangaonline.examples.model;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "Lecturer")
public class Lecturer implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String lecName;

    public Long getId() {
        return id;
    }

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

    public String getLecName() {
        return lecName;
    }

    public void setLecName(String lecName) {
        this.lecName = lecName;
    }
}




Course.java

package com.chathurangaonline.examples.model;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "Course")
public class Course implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

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

    @ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name = "lecturer_id")
    private Lecturer lecturer;

    public Long getId() {
        return id;
    }

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

    public String getCourseName() {
        return courseName;
    }

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

    public Lecturer getLecturer() {
        return lecturer;
    }

    public void setLecturer(Lecturer lecturer) {
        this.lecturer = lecturer;
    }
}

Hope this will be helpful for you!

Cheers
Chathuranga Tennakoon
chathuranga.t@gmail.com

Monday, September 30, 2013

How to generate JAX-WS client and integrate with client application

 my previous post explained about  how to deploy the web service in the tomcat web server.   So, our web service is up and running now. it is time to create/generate the web service client and integrate it with our application.

  we can generate the Web Service client from the WSDL file. wsimport utility will help to generate java based web service client from the given WSDL.So in our scenario, we can generate the web service client with following linux command.

wsimport  -keep  -verbose  -d <directory_to_create_web_service_client>  <wsdl_url>

-verborse (print the status of the operation being  executed to the terminal)
 -d  (path to the directory where the web service client should be created)

 wsimport  -keep  -verbose -d /home/chathuranga/java/jax-ws/client  http://localhost:8080/calculator-service/calcServiceUrl?wsdl 


now we have successfully completed the process of generating the web service client. it can be integrated with your application now.

The source code for the complete example can be found at following github url.


Hope this will helpful for you!

Cheers
Chathuranga Tennakoon
chathuranga.t@gmail.com






Thursday, September 26, 2013

Deploy JAX-WS web service in Tomcat Server

if the web service is going to be deployed in the tomcat server,it has to be developed as a web application project with some added configurations.
in order to start the web application project, i prefer to use maven archetype generate command as follows.

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp


then it will give me a basic web application project that can be built with maven.
now this is the time to integrate my predefined web service with the web application project.

1. first create the relevant package structure in the web-app project and copy the web service src files there.


2. create the web service deployment descriptor ( sun-jaxws.xml ) file under the webapp/WEB-INF directory. (same directory where the web.xml resides).
 the endpoints should be defined as follows.

<?xml version="1.0" encoding="UTF-8"?>

<endpoints
        xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
        version="2.0">
    <endpoint
            name="calcService"     
            implementation="com.chathurangaonline.jaxws.samples.impl.CalculatorServiceImpl"

            url-pattern="/calcServiceUrl"/>
</endpoints>




3. in web.xml file (standard deployment descriptor) defines the WSServletContextListener and WSServlet class as follows.

<!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>Archetype Created Web Application</display-name>

   <listener>
      <listener-class>
            com.sun.xml.ws.transport.http.servlet.WSServletContextListener
       </listener-class>
    </listener>

    <servlet>
        <servlet-name>calcService</servlet-name>
        <servlet-class>
            com.sun.xml.ws.transport.http.servlet.WSServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>calcService</servlet-name>
        <url-pattern>/calcServiceUrl</url-pattern>
    </servlet-mapping>

</web-app>



3.  if you do all the above steps correctly, you project structure should be as follows.




now it is the time to build the web service. since the web service is published in the tomcat server, it should be built as a WAR file similar to simple web app.



4.  once the web service is compiled and package, copy the WAR file to the webapps directory in the tomcat server.


5. sometimes the web service not be loaded because the tomcat does not have the required libraries to server for web services (By default, Tomcat does not comes with any JAX-WS dependencies). In that case you need to download those dependencies and copy to the “${Tomcat}/lib” directory.

  •  Go here http://jax-ws.java.net/
  • Download JAX-WS RI distribution.
  • Unzip it and copy following JAX-WS dependencies to Tomcat library folder “{$TOMCAT}/lib“.
    • jaxb-impl.jar
    • jaxws-api.jar
    • jaxws-rt.jar
    • gmbal-api-only.jar
    • management-api.jar
    • stax-ex.jar
    • streambuffer.jar
    • policy.jar

once the above depdencies are copied, restart the tomcat server and try to access the web serice with following URL.

http://localhost:8080/calculator-service/calcServiceUrl

if the web service is working, it should display the following page in the browser.
then we are done.




Summary

the all steps taken for publishing a web service in tomcat can be summarized as below.
  1. Create a web service
  2. Create a sun-jaxws.xml, defines web service implementation class.
  3. Create a standard web.xml, defines WSServletContextListener, WSServlet and structure of a web project
  4. Copy JAX-WS dependencies to “${Tomcat}/lib” directory.
  5. Generate WAR file and copy to “${Tomcat}/webapp” directory.
  6. access the web service from browser and check whether it is up and running.


 SOURCE CODE : - https://github.com/chathurangat/jaxws-calculator-service-webapp

Hope this might be helpful for you!

Cheers
Chathuranga Tennakoon


Thursday, September 19, 2013

Simple JAX-WS Webservice - Calculator Implementation

First we will create a Simple JAX-WS Web Service. if you do not know how to create such web service, you can refer my previous article that describes how to develop simple JAX-WS Service.

Click Here to See How To Create Simple JAX-WS Service

i assumed that you have created a simple web service and it is up and running. we will modify that web service to provide the calculator based web service operations. in this calculator web service, we support for three operations.

1. Addition
2. Multiplication
3. Subtraction

you can see the SEI (Service Endpoint Interface) and SIB (Service Implementation Bean) as follows.


SEI - CalculatorService.java

package com.chathurangaonline.sample.jaxws;

import javax.jws.WebMethod;
import javax.jws.WebService;

/**
 * <p>
 *     Service Endpoint Interface for the calculator service.
 * </p>
 */
@WebService
public interface CalculatorService {

    @WebMethod
    long add(long number1, long number2);

    @WebMethod
    long subtract(long number1, long number2);

    @WebMethod
    long multiply(long number1, long number2);
}


SIB - CalculatorServiceImpl.java

package com.chathurangaonline.sample.jaxws;

import javax.jws.WebService;

/**
 * <p>
 *     Service Implementation Bean (SIB) for CalculatorService endpoint interface
 * </p>
 */
@WebService
public class CalculatorServiceImpl implements CalculatorService{


    @Override
    public long add(long number1, long number2) {
        return number1+number2;
    }

    @Override
    public long subtract(long number1, long number2) {
        return number1+number2;
    }

    @Override
    public long multiply(long number1, long number2) {
        return number1*number2;
    }
}


Service Publisher (Only for Development Environment)

package com.chathurangaonline.sample.jaxws;

import javax.xml.ws.Endpoint;

/**
 * <p>
 *     simple web service publisher for testing the web service in the development environment.
 *     remove this publisher class in the production environment and deploy the web service with
 *     j2ee compliant web server.
 * </p>
 */
public class CalculatorServicePublisher {

    public static void main(String[] args) {

        Endpoint.publish("http://localhost:6655/jaxWsCalcService",new CalculatorServiceImpl());
    }
}


once everything is added correctly, our project will looks like as follows.



now we have a calculator web service that is ready for the deployment. now we will publish our web service using the Endpoint.publish() method and check whether it is working. since we are uisng this in the test environment, we do not need to deploy this is a J2EE application server at the moment. but in our next article we will look at how to deploy the web service in tomcat server.

once the web service is published you can access the web service in the following url.
http://localhost:6655/jaxWsCalcService

once the web service is published, we need to write/generate a web service client to comsume the web service. it will be discussed in following blog post.


How to generate JAX-WS service client and integrate with Java Application

you can download the source code from following gitHub repo.

https://github.com/chathurangat/jaxws-calculator-service

Hope this will be helpful for you!

Cheers
Chathuranga Tennakoon
www.chathurangaonline.com







Tuesday, September 17, 2013

how to exclude web service operation (web method) from the web service in jax-ws

The annotation @WebService tells the server runtime environment to expose all public methods on that bean as a Web service. In below example, all the public methods in the web service will be exposed as web methods.


package com.chathurangaonline.sample.jax.ws;
 
import javax.jws.WebService;
import com.chathurangaonline.sample.model.Hotel;
 
@WebService
public class HotelWebService{
 
    public Hotel retriveHolelByCity(String cityName) {
        //todo implementation should goes here 
        return new Hotel();
    }


    public void addNewHotel(Hotel hotel) {
        //todo implementation should goes here 
    }
}


suppose that you do not need to expose the  addNewHotel method as a web service operation method. but the default implementation of the @WebService method will expose all public methods as web service operations. but there is a special annotation that will prevent the method by exposing/publishing as a web service operation.

    @WebMethod(exclude = true)


Refer the below class and try to publish the web service.

package com.chathurangaonline.sample.jax.ws;
 
import javax.jws.WebService;
import com.chathurangaonline.sample.model.Hotel;
 
@WebService
public class HotelWebService{
 
    public Hotel retriveHolelByCity(String cityName) 
        //todo implementation should goes here 
        return new Hotel();
    }


    @WebMethod(exclude = true)
    public void addNewHotel(Hotel hotel) {
        //todo implementation should goes here 
    }
}


here the  addNewHotel method will not be exposed or published as a web service operation/method.

i hope that this will be helpful for you!

Cheers
Chathuranga Tennakoon
chathuranga.t@gmail.com
www.chathurangaonline.com  

Friday, August 30, 2013

Compound Primary Keys in Hibernate using Annotations

most of the cases, identifier (primary key) of the entity will be a single attribute. but there will be some cases where the primary key of the entity will be comprised by several attributes. In other words, primary key will consist of more than one column. if the primary key consist of more than one attribute/column, we called it as composite primary key or compound primary key.

  In hibernate, there are three ways that can be used to create compound primary key in a entity class using annotations. In all of these three scenarios, it will be required to create a separate class for the compound primary key.

1. Compound primary key with  @Embeddable annotation
 mark the compound primary key (PK) class with @Embeddable annotation and  add the instance of the PK class to the entity class as a normal property. then mark it with @Id annotation as usual.


2. Compound Primary key with @EmbeddableId annotation
 create the compound PK class as  POJO (Plain Old Java Object) and add it as a normal property for the Entity class. then mark that instance with @EmbeddableId annotation.


3. Compound Primary key with @IdClass annotation
    declare the compound primary key class with @IdClass annotation and add the all primary key properties of that class to the entity class as normal properties. then mark all the added primary key properties with @Id annotation.



Hope this will be helpful for you!

Cheers
Chathuranga Tennakoon
www.chathurangaonline.com

Tuesday, August 20, 2013

Hibernate 4 - One to Many mapping with Annotations (LAZY loading example)

 the technologies i ma using for this example.

Hibernate 4
testNG for TDD
MySQL
Maven

In this example, we are going to use our Lecturer and Course example again the entity relationship will be decided based on the following assumption.

Assumption:
 Lecturer can teach many number of courses.

Therefore the relationship between two entities can be described as follows.

  •  relationship from Lecturer to Course is One-To-Many (lecturer can teach many number of courses) 
  •  relationship from Course to Lecturer is Many-To-One (many courses will be taught by one lecturer)
Refer the below example.

Lecturer.java
package com.chathurangaonline.examples.model;

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

@Entity
@Table(name = "Lecturer")
public class Lecturer implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL,mappedBy = "lecturer")
    private List courseList;

    public Long getId() {
        return id;
    }

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

    public List getCourseList() {
        return courseList;
    }

    public void setCourseList(List courseList) {
        this.courseList = courseList;
    }
}





Course.java
package com.chathurangaonline.examples.model;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "Course")
public class Course implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

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

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "lecturer_id")
    private Lecturer lecturer;

    public Long getId() {
        return id;
    }

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

    public String getCourseName() {
        return courseName;
    }

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

    public Lecturer getLecturer() {
        return lecturer;
    }

    public void setLecturer(Lecturer lecturer) {
        this.lecturer = lecturer;
    }
}




i have used the following code to check the mapping relationship  and the lazy loading.



    @Test
    public void testSave() throws Exception {

        //saving the lecturer
        Lecturer lecturer = new Lecturer();
        lecturerDao.save(lecturer);
        Assert.assertNotNull(lecturer.getId());

        //saving the course
        Course course = new Course();
        course.setCourseName("Java");
        course.setLecturer(lecturer);
        courseDao.save(course);
        Assert.assertNotNull(course.getId());

        System.out.println(" retrieving the lecturer record with id ["+lecturer.getId()+"]");
        Lecturer  lecturer2  = lecturerDao.findById(lecturer.getId());
        System.out.println("lecturer found with id ["+lecturer2.getId()+"] retrieved");
        System.out.println("course retrieving .......");
        List  courseList1 = lecturer2.getCourseList();
        System.out.println(" course list retrieved ["+courseList1.size()+"]");
    }


when i run the above code, i got the following output and seems to be that the lazy loading is also working fine.



you can get the example source code from following gitHub repository.
Get SourceCode from GitHub


Hope this will be helpful for you!

Cheers
Chathuranga Tennakoon
chathuranga.t@gmail.com
www.chathurangaonline.com


Monday, August 12, 2013

Lazy loading not wotking with hibernate OneToOne mapping

in my experience, i have encountered an issue that the hibernate lazy loading is not working when we map the relationship between two entities  using OneToOne annotations.see the following examples.

Lecturer.java

package com.chathurangaonline.examples.model;



import javax.persistence.*;

import java.io.Serializable;



@Entity
@Table(name = "Lecturer")
public class Lecturer implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;


    @OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name = "course_id")
    private Course course;


    public Long getId() {
        return id;
    }


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


    public Course getCourse() {
        return course;
    }


    public void setCourse(Course course) {
        this.course = course;
    }
}





Course.java

package com.chathurangaonline.examples.model;


import javax.persistence.*;
import java.io.Serializable;


@Entity
@Table(name = "Course")
public class Course implements Serializable{

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;


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


    @OneToOne(fetch = FetchType.LAZY,mappedBy = "course")
    private Lecturer lecturer;


    public Long getId() {
        return id;
    }


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


    public String getCourseName() {
        return courseName;
    }


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


    public Lecturer getLecturer() {
        return lecturer;
    }


    public void setLecturer(Lecturer lecturer) {
        this.lecturer = lecturer;
    }
}



you will notice that the mapping from the lecturer to course is One-To-One and the fetch type is LAZY. Since the fetch type is LAZY, the associated course object should not be loaded when the lecturer object is loaded. the associated course object should be loaded only when the user request it. that is the behavior of the lazy fetch mode.

    but in this example, you will notice that course object is loaded (EAGER resolved) when the time that the lecturer object is loaded regardless of the LAZY fetch type. it always eagerly resolve the associated entities even if it is declared as LAZY fetch. . please refer the below screenshot.


you will see that when retrieving the Lecturer object with given id, it generates and issue a SQL query to retrieve data from the database. when the lecturer object is retrieved, it loads and populates the associated course object also. that is why when we request the course object and its attributes, it directly give the values of the attributes without issuing another SQL query. the reason for this EAGER behavior can be described as follows.


    @OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name = "course_id")
    private Course course;

you will notice that the OneToOne relationship is not mandatory and it is optional.(by default, the optional=true). since the relationship is optional, hibernate(ORM framework) does not know whether the given lecturer teach a course or not without issuing an another query. therefore hibernate cannot populate the course reference with a proxy, because it does not know whether a course exists for that lecturer.  On the other hand, it cannot populate the course attribute with null because, there may be lecturers who teach courses. therefore hibernate performs the EAGER loading regardless of the LAZY fetch mode if the relationship is OneToOne and it is optional.

to overcome to above issue and make the LAZY loading working, you need to make the relationship as mandatory. In oder to do that, set the optional=false.

   @OneToOne(fetch = FetchType.LAZY,
                        cascade = CascadeType.ALL,
                        optional = false)
   @JoinColumn(name = "course_id")
   private Course course;



then the lazy loading should works as usual.
refer the following screenshot and identify how the lazy loading works. refer the below screenshot.


you will see that when retrieving the associated course instance from the lecturer instance, it generates another SQL queries to retrieve the course details associated. this is because the Fetch type of the relationship is LAZY.


references :
http://stackoverflow.com/questions/17987638/hibernate-one-to-one-lazy-loading-optional-false


Hope this will be helpful for you!

Thanks
Chathuranga Tennakoon
chathuranga.t@gmail.com
www.chathurangaonline.com







Tuesday, August 6, 2013

XML based mapping VS Annotation based mapping in hibernate

There are two ways that we can perform entity mapping in hibernate.
1. XML based mapping
2. Annotation based mapping.

the intention of this article is to select the appropriate mapping option for your project. by the way, i always prefer the annotation based mapping for my projects because of the following reasons.

  • i personally hate a load of XML mapping files and it adds unnecessary complexity for the project. 
  • it degrade the readability and understandability of the code because your POJO (Plain Old Java Objects) is independent from the relevant XML mapping files. therefore you cannot understand the database constraints, associations and mapping relationships between entities just looking at only the POJOs. you need an additional effort to read the XML mapping files and POJOs simultaneously to get an understanding of how entity mapping has been done.

 i personally prefer the annotation based mapping because of the following reasons.

  •  it is very simple to perform entity mapping with annotations and i don't have to maintain separate XML configuration files. 
  • In Annotation mapping,the entity relationships, mappings and other DB constraints are also defined in the POJO along with the relevant attribute. therefore it improves the understandability and the readability of the code.

The decision of selecting the appropriate mapping option (either Annotation based or XML based) for your project should be done wisely.

when to use XML based mapping


it is safer to use XML based mapping to integrate/use the hibernate for a project that is already developed. since you are using XML based mapping, you do not have to touch or modify the POJO classes that are already developed and stable. if you are confident enough to modify the POJOs, then you may use annotation based mapping.(But not recommended)

Another scenario where we can use the XML based mapping is that, we are getting a request  to integrate/use the hibernate for a project that is already developed. but the problem is we do not have the source code of the POJO classes. at that time, we cannot use the annotation to map the entities because, we do not have the source code of POJOs. in such case, we have to use the XML based mapping.


when to use the Annotation based mapping

XML based mapping is a proprietary format of Hibernate ORM framework.
if you intend to expose your applications to other JPA2 compliant other ORM frameworks, you must use the Annotation based mapping. but keep it in mid that there are two types of annotations.
  •  Annotations in the javax.persistance package
In oder to comply, your application with the JPA 2 specification standards, you must use the annotations provided in this package.
  •  Annotations in the org.hibernate package
Annotations provided in this package also specific to the hibernate. In otherwords, all these annotations are owned and governed by the hibernate. therefore  if you have used this annotations,your application will not comply with JPA 2. therefore the application will not work with other ORM frameworks compliant with JPA2. therefore using these annotations will produce the same effect as XML based mapping. only difference between the XML and Annotation (org.hibernate package) based mapping is that it is XML and this is annotations.



Hope this will be helpful for you!
Cheers
Chathuranga Tennakoon
www.chathurangaonline.com

Friday, August 2, 2013

Hibernate One To One Bidirectional Mapping with Annotations

Assumption : Lecturer can teach only one Course and the given Course can be taught only by one lecturer.  therefore we will use One To One mapping here

Lecturer.java


package com.chathurangaonline.examples.model;

import javax.persistence.*;

@Entity
@Table(name = "Lecturer")
public class Lecturer {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL,optional=false)
    @JoinColumn(name = "course_id")
    private Course course;

    public Long getId() {
        return id;
    }

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

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

}




Course.java

package com.chathurangaonline.examples.model;

import javax.persistence.*;

@Entity
@Table(name = "Course")
public class Course {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

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

    @OneToOne(mappedBy = "course",fetch = FetchType.LAZY)
    private Lecturer lecturer;

    public Long getId() {
        return id;
    }

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

    public String getCourseName() {
        return courseName;
    }

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

    public Lecturer getLecturer() {
        return lecturer;
    }

    public void setLecturer(Lecturer lecturer) {
        this.lecturer = lecturer;
    }
}



you will see that there is a mapping relationship between Lecturer and Course entities. this relationship is  bidirectional mapping relationship because each entity contain the reference for other entity. in bidirectional relationship, one entity will manage and own the foreign key relationship. it is the entity that holds the forien key too.

what is mappedBy atrribute?

as i have described above, in bidirectional relationship one entity will own  and manage the foreign key relationship. the other entity (which does not manage the foreign key) uses the mappedBy attribute to tell that who is the owner of the foreign key relationship.

    @OneToOne(mappedBy = "course",fetch = FetchType.LAZY)
    private Lecturer lecturer;

 in this example, mappedBy attributes says that "Hey, i am not the owner of the foreign key and i do not manage it.  it is owned and managed by the course attribute belongs to the Lecturer entity.


Hope this will helpful for you.

Cheers
Chathuranga Tennakoon
www.chathurangaonline.com

Thursday, August 1, 2013

Android Development- Setting Up development environment and Hello World Application

I have decided to start new post series on Android Application development. Before starting the android application development, we need to set up our development environment.

Here I am using the Eclipse IDE for the android application development. In order to set up the android development environment in the existing Eclipse IDE, it is required to install few software tools (Android SDK, ADT plugin etc). I feel like it will take some time and effort to install that in my existing Eclipse IDE. Therefore I downloaded the ADT bundle and extract it. That can be downloaded through the following URL. Make sure that you are downloading the correct version that is compatible with your operating system of the computer.

http://developer.android.com/sdk/index.html

After extracting it ,i was able to find the Eclipse IDE version with build in ADT(Android Development Tools) and components that are essentially required to develop the android apps. I would like to thank to the contributors and the team members of the ADT bundle project team to save my time. By the way, if you wish to configure your existing Eclipse IDE as android development environment, you can refer the following links to do so.

http://developer.android.com/sdk/installing/installing-adt.html

Lets start with the project development now.  As a practice we will try to develop a simple  “Hello World” application to understand the android project structure. You can refer the following link to
create the simple App.

https://developer.android.com/training/basics/firstapp/creating-project.html

once the project is built, it took a long time to load the application on the AVD(Android Virtual Device) emulator and I felt like uncomfortable of wasting such time. Therefore I tried to test the app in my mobile and it took only few seconds. But first time I was deploying my app on the mobile it gives me the following error.

INSTALL_FAILED_INSUFFICIENT_STORAGE

The INSTALL_FAILED_INSUFFICIENT_STORAGE error is the bane of every Android developer's life. It happens regardless of app size, or how much storage is available.

There is a simple workaround. If your test device is running Android 2.2 or later then add the android:installLocation attribute to your application's manifest file, with the value "preferExternal". This will force the app to be installed on the device's external storage, such as a phone's SD card.
For example:

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.andrewsmith.android.darkness"
    android:installLocation="preferExternal"

I hope that this will be helpful for the new android developers to start their android development on the correct track. If you have any question, you can contact me on chathuranga.t@gmail.com or www.chathurangaonline.com

Cheers
Chathuranga

Monday, July 22, 2013

Simple JAX-WS Web Service (SOAP based) for Beginners


Today, i am going to explain simple JAX-WS web service( based on SOAP) for the beginners who are new to web service development. 
Web Services can be divided into two categories.
1. SOAP based web services
2. RESTful web services.

JAX-WS supports for both SOAP based and RESTful web services. In this post, we are going to discuss about the SOAP based web services. AS an entry point for the SOAP web service, first we will discuss the architecture of the typical SOAP based web service.


 


Here you can see that the SOAP client will communicate with the SOAP service with the aid of the SOAP libraries. SOAP libraries will be responsible to send and receive request and response between client and server. Here the both request and response will be the SOAP documents and those will be exchanged between client underlying SOAP libraries and the Service underlying SOAP libraries. These SOAP libraries will do the marshalling and unmarshaling whenever required.

What is marshalling and unmarshalling?

Marshalling – converting Java objects into the XML files.
Unmarshalling - converting XML files into the Java objects.

JAX-WS uses JAXB (Java Architecture for XML Binding) for the marshalling and unmarshalling.


In this example, we are going to look at the simple SOAP based 
web service that prints the hello concatenating with the provided 
web service input parameter as the output. Refer the below project 
tree structure to identify the components associated with the 
web service.


 
I will briefly explain the web service concepts by getting the
 examples from above sample web service.
  • Service Endpoint Interface (SEI) – HelloWorld.java 
  • Service Implementation Bean (SIB) – HelloWorldImpl.java
  • Web Service Publisher - HelloWorldPublisher.java 
Then we need to look at SEI, SIB and WsPublisher in detail.


SEI : - Service  Endpoint Interface
first of all you need to know what is the SEI. SEI is just a Java interface
that defines/declares all the web service methods. In this example,
the following file will be the SEI.

HelloWorld.java
package com.jax.ws.samples;

import javax.jws.WebMethod;
import javax.jws.WebService;

/**
 * <p>
 *     this will be the SEI that declares all the web service methods
 * </p>
 */
@WebService
public interface HelloWorld {

    @WebMethod
    String printWelcomeMessage(String username);
} 
SIB :- Service Implementation Bean SIB is the implementation of SEI. That means in the SIB, all the 
web methods declared in the SEI will be implemented.
SIB can be implemented as two ways.
 
 1. POJO class
2. Stateless Session EJB

In this example will be using POJO class as SIB to implement SEI as follows.

HelloWorldImpl.java

package com.jax.ws.samples;

import javax.jws.WebService;

/**
 * <p>
 *     this will be the SIB that implements all the web service methods
 *     declared in the SEI.
 * </p>
 */
@WebService(endpointInterface = "com.jax.ws.samples.HelloWorld")
public class HelloWorldImpl implements HelloWorld{

    @Override
    public String printWelcomeMessage(String username) {
        return "Hello "+username;
    }
}
as you can see, the end point interface will be the relevant java 
interface (SEI) that is implemented by the relevant SIB.


Publishing the Web Service 
once the SEI and SIB have been completed  and compiled, the web 
service is ready to be published. In production mode,web service 
should be published using the application servers such as Tomcat, 
JBoss, WebLogic etc... but for the testing purpose it is possible to 
publish the web service with the simple java program as follows.

HelloWorldPublisher.java

package com.jax.ws.samples;

import javax.xml.ws.Endpoint;
/**
 * <p>
 *     this will be the sample web service publisher class
 *     whose responsibility to publish the given web service
 * </p>
 */
public class HelloWorldPublisher {

    public static void main(String []args){
        //1st argument - web service publication URL
        //2nd argument - instance of SIB
        Endpoint.publish("http://localhost:6666/sayHello",new HelloWorldImpl());
    }
}

you can publish the web service by running this simple program (HelloWorldPublisher.java). After running the publisher program, it is time to check whether the 
published web service is up and running. This can be done with web 
browser by getting the related WSDL document as follows.
 
http://localhost:9999/sayHello?wsdl


I think this will be helpful for you to start your first Java web service development.

This sample web service is available in the following GitHub repository. 
https://github.com/chathurangat/jax-ws-helloworld
 
I think this will give you an brief idea about how to develop web services with java. 
Hope this will helpful for you
 
Thanks and Regards
Chathuranga Tennakoon
 

Wednesday, July 17, 2013

Difference between Unidirectional and Bidirectional mapping in hibernate


Unidirectional Mapping

When only one of the pair of entities contains a reference to the other, the association is unidirectional. for example, assume that there are two entities called Lecturer and Course.

In unidirectional mapping, the lecturer will hold a reference for the course OR course will hold a reference for the lecturer.(Not Both) It is mandatory that the references should not be mapped to the both directions and there should be only one direction(unidirectional) mapping.

In unidirectional mapping, it will provide the navigational access only to one direction.

eg:-

assumption: lecturer can teach only once course and a given course can be taught only by one lecturer

unidirectional mapping  from lecturer to course

class Lecturer{

   private Long id;
   private  String lecturerName;
   private Course;

   //getter and setters
}


class Course{
 
   private Long id;
   private String courseName;

    //getter and setters
}


unidirectional mapping  from course to lecturer


class Lecturer{

   private Long id;
   private  String lecturerName;


   //getter and setters
}


class Course{
 
   private Long id;
   private String courseName;
   private Lecturer lecturer;

    //getter and setters
}



Bidirectional Mapping

if the association between both entities are mutual, then it is known as bidirectional mapping. in bidirectional mapping, the lecturer should hold to a reference for the course and the same time the course should a reference to the lecturer.

therefore in bi-directional mapping, it will provide the navigational access to the both directions.

eg:-
assumption: lecturer can teach only once course and a given course can be taught only by one lecturer

class Lecturer{

   private Long id;
   private  String lecturerName;
   private Course;

   //getter and setters
}


class Course{
 
   private Long id;
   private String courseName;
   private Lecturer lecturer;

    //getter and setters
}


hope this will help for you!

Cheers
Chathuranga Tennakoon
www.chathurangaonline.com


Saturday, June 15, 2013

What is SAML (Security Assertion Markup Language) 2.0 ?

Security Assertion Markup Language 2.0 (SAML 2.0) is a version of the SAML OASIS standard for exchanging authentication and authorization data between security domains. SAML 2.0 is an XML-based protocol that uses security tokens containing assertions to pass information about a principal (usually an end user) between an identity provider and a web service. SAML 2.0 enables web-based authentication and authorization scenarios including single sign-on (SSO).

Friday, May 17, 2013

Create Vaadin project with maven

-->
today i am going to show you how to create a Vaadin project using maven. I am going to create a project that uses Vaadin 7.0.5. My development environment is as follows.

  • Ubuntu OS
  • JDK 7
  • maven 3
  • Intelli J IDEA 12
  • Apache tomcat 7

I am using ubuntu terminal throughout the development.

mvn archetype:generate \
   -DarchetypeGroupId=com.vaadin \
   -DarchetypeArtifactId=vaadin-archetype-application \
   -DarchetypeVersion=7.0.5 \
   -Dpackaging=war

then fill the required details as follows.


groupId - org.fosshub.vaadin
artifactId - vaadin-web-app
version - 1.0
package - org.fosshub.vaadin.sample

after creating the project, you can open the project with your preferred IDE. I am using IntelliJIDEA.
The opened project structure will be as follows.

now you can start coding with your created vaadin project.

Regards
Chathuranga Tennakoon

Friday, May 3, 2013

Spring Security - form based login + user details in XML + url based access control

this will be the first article that i am writing about the practical implementation of the Spring Security. throughout this article i am expecting to how the Spring Security framework is practically integrated with your Spring MVC Web Application. 

 Those who are new to Spring MVC can refer Spring MVC Web Application article before proceeding with this article. others can download the below source code to continue with this article.


expectation of this article is to discuss the following areas.

1. Form based user authentication with XML based userDetailsService
    (this userDetailsService is known as the In-Memory user detail service)

2. URL based access control with Spring Security


first open the project with your IDE.In my case, i am using Intelli J IDEA.  then you will see the overall project file and directory structure as follows.



then we can proceed with Spring Security Integration for this web application.

first we will look at why spring security is such important. as you are aware, each application can have several user levels. each user level is attached with set of  specific privileges known as user permissions. we should be able to restrict/grant the access for the different areas of the application based on the user level permissions. in order to archive that purpose, we will be using spring security framework. simply, Spring security will be used to control the user access (Access Control) of the application.


the application has not been integrated with the spring security framework yet. therefore you will find following security vulnerabilities of this application.

  1. non-authenticated users(guests) can access the home page dedicated for the authenticated users.    
        http://localhost:8080/spring-mvc-sample/user/home

  1. non-authenticated users(guests) can access the home page dedicated for the admin users.
         http://localhost:8080/spring-mvc-sample/user/admin/welcome


Now we are going to integrate the Spring Security framework with this web application to fix those security vulnerabilities. you can refer the following step to to integrate spring security with sample Spring MVC application given above.


  • first add the Spring Security maven dependency for the pom.xml file.
  •  then do the following spring security filter mapping in the web.xml file
    
  • then add a spring configuration xml file called spring-security.xml directly under the WEB-INF directory of the web application.  your spring-security.xml file should contains following security configurations and declarations.
      

  • finally location of the spring-security.xml file should be passed to the Spring Framework's ContextLoaderListener as contextConfiguration parameter. that can be done by modifying the contextConfigurationLocation parameter of the web.ml as follows.


Now you have successfully integrated your web application with Spring Security Framework.


now you can use following login credentials to check whether the above identified security vulnerabilities still exist.

User Credentials (who has ROLE_USER)

username : chathuranga
password : admin

Admin User Credentials (who has ROLE_ADMIN and ROLE_USER)

username : darshana
password : admin

completed source code of this post can be found at GitHub


i think this post might help you to get some understading of spring security.

Thanks and Regards
Chathuranga Tennakoon
chathuranga.t@gmail.com
http://lk.linkedin.com/in/chathurangatennakoon


Thursday, April 18, 2013

Class variable Vs Instance variable in java


-->
both variables are defined inside the class and outside to any method. Therefore both of these variables are in the class scope.

Instance variable
instance variable belongs to an instance of a class. Each instance of the class maintain its own copy of the instance variable(s). Therefore the changes or operations that are done with an instance variable will only be reflected in that instance variable. (no other instance variables are affected)

here is an example for the instance variable.

class sampleClass{

    int count;
}


Class variable
class variables are known as static member variables. Class variable is common to the all instances of the class. In other words, one class variable will be shared with all instances of the class. Class variables are modified with static modifier.

Here is an example for the class variable.

Class sampleClass{
   
    static int count;
}

instance variable and class variable.
Each object(instance) in the class has its own copy of instance variables. But every instances(objects) in the class will be shared one copy of class variables. Therefore the changes that are done for the instance variables will only be visible to that particular instance. But the changes that are done for class variables will be visible to all the instances of that class. This is because the class variables are shared among all instances of the class. Both class variable and member variables have been identified as a member variable of a class.


Hope this will helpful for you!

Regards
Chathuranga Tennakoon

Tuesday, January 1, 2013

Adding the executing order for the Servlet 3 Annotation based Filter classes

welcome to my first post o the year 2013 ;) and i today decided to investigate through servlet 3.0 features.  as you all are aware servlet 3 has a nice feature called annotations. therefore we can minimize the XML based declarations on the web.xml deployment descriptor. today i am going to show a simple demonstration on annotated servlet filters and how to add execution order for those servlet filters.

you can generate simple web application project with  following maven command.

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp

one the project is generate, make sure to check and alter the web application deployment descriptor based on the servlet 3 API version . i have post a article about deployment descriptors(web.xml) for different servlet versions   and you can refer that article if you dont know how to do that and what is the purpose of doing that.

after creating the project, add following servlet3 maven dependency for the pom.xml of your project.

then add the following two filters also. you can see that here we are using the annotated servlet filters. 
 FilterOne.java  
FilterTwo.java  

if you need you can add the following servlet class also.  
HelloServlet.java 

you can deploy the web application in the tomcat and access the web application as follows.

http://localhost:8080/sample-servlet3-webapp/hello

then you will get the following result(check the application loggers).
inside the filter one
inside the filter two 
this servlet will be executed after executing the all relevant filters  according to their order 

you can get the full source code from my GitHub account Download Source code through GitHub