Enetrprice Java Bean - bean life cycles

Stateless session bean - life cycle



uncreted state -> active state (setSession() from container and ejbCreate() )
active state -> destroy state (ejbRemove())


Statefull session bean - life cycle

Uncreated state -> Active state (setSession() from container and ejbCreate() )
Active state -> Passive state (ejbPassivate() )
Passive state -> Active state (ejbActivate() , bean can only be invoked when active )
Active state -> Destroy state (ejbRemove() )

Entity bean - life cycle


Uncreated -> Pool state (setEntityContext(), Now entity bean is just created and in a pool. No id is assigned)
Pool state -> Active (create(), ejbActivate(), ejbCreate(). Now it has an id)
Active state -> Pooled state (ejbPassivate(), remove(), ejbRemove() )
Active state -> destroy state (unsetEntityContext())

Message driven bean - life cycle

Uncreated -> Active state (setEntityContext()ejbCreate())
Active state -> Event listening state (onMessage(), bean can react to incoming events to now )
Active state -> destroy state (ejbRemove())
Share:

Enterprice Java Beans on JBoss (Wildfly now)

EJBs are associated with applications and it can do application's work. It's that simple. So these applications have to be deployed on a server. For the server you have various servers to choose.

  • Apche
  • IBM websphere application server
  • JBoss (now called as WildFly)
  • OW2
  • Oracle GlassFish
  • Resin and many more.
But for now we will focus on WildFly server more particularly 9.x.
PS- If you haven't install WildFly  you can do this with ecilpse's servers tab. And configure it with correct HOME_PATH for WildFly.

Before we going down further,lets make clear of this thing.

Session bean:
  • Session beans contain business logic.
  • State-full session beans cant be reused again and again. One instance/session per client. Destroy and re create
  • Stateless sessions beans can be reused and shared across multiple clients
  • Singleton session beans are 1 per application
Entity bean is simply a representation of table raw. Which means it should be uniquely identifiable from other entity bean instances. For this we can use the existing table row primary key(PK). This can be composed of a single primary key or a composition of different primary keys.

Characteristics of entity bean PK
  • It should be a type of integer wrapper class
  • Should be unique
  • Should have proper annotations 
Entity bean:
  • Can maintain its state with a unique primary key. So even in a system shutdown these can be persistent coz it has a unique primary key.
  • At a time can be associated with multiple clients
  • Represents a row in a table. Meaning entity bean and a data source has an association 

Minimum code for a Session bean implementation

package Session;

import java.rmi.RemoteException;

import javax.ejb.EJBException;
import javax.ejb.LocalBean;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;

/**
 * Session Bean implementation class MySessionEJB
 */
@Stateless
@LocalBean
public class MySessionEJB implements SessionBean {

    /**
     * Default constructor. 
     */
    public MySessionEJB() {
    }

 @Override
 public void ejbActivate() throws EJBException, RemoteException {
  
 }

 @Override
 public void ejbPassivate() throws EJBException, RemoteException {
  
 }

 @Override
 public void ejbRemove() throws EJBException, RemoteException {
  
 }

 @Override
 public void setSessionContext(SessionContext arg0) throws EJBException, RemoteException {
  
 }
 
 // additional user defined methods
 public int multiply(int x, int y)
 {
  return x*y;
 }

}


Minimum code for a Entity bean implementation

package Entity;

import java.rmi.RemoteException;

import javax.ejb.EJBException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.LocalBean;
import javax.ejb.RemoveException;
import javax.ejb.Stateless;

/**
 * Session Bean implementation class MyEntityBean
 */

public class MyEntityBean implements EntityBean {

    @Id // Indicates this is an ID
 @TableGenerator(name="") // Name of the table
 @Column() // Unique column name
 Integer primaryKey;
 
 public Integer getPrimaryKey()
 {
  return primaryKey;
 }

     /**
     * Default constructor. 
     */
    public MyEntityBean() {
    }

 @Override
 public void ejbActivate() throws EJBException, RemoteException {
  
 }

 @Override
 public void ejbLoad() throws EJBException, RemoteException {
  
 }

 @Override
 public void ejbPassivate() throws EJBException, RemoteException {
  
 }

 @Override
 public void ejbRemove() throws RemoveException, EJBException, RemoteException {
  
 }

 @Override
 public void ejbStore() throws EJBException, RemoteException {
  
 }

 @Override
 public void setEntityContext(EntityContext arg0) throws EJBException, RemoteException {
  
 }

 @Override
 public void unsetEntityContext() throws EJBException, RemoteException {
  
 }

}

Minimum code for a Message bean implementation

package Message;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;

/**
 * Message-Driven Bean implementation class for: MyMessageBean
 */
@MessageDriven(
  activationConfig = { @ActivationConfigProperty(
    propertyName = "destinationType", propertyValue = "javax.jms.Queue")
  })
public class MyMessageBean implements MessageListener {

    /**
     * Default constructor. 
     */
    public MyMessageBean() {
    }
 
 /**
     * @see MessageListener#onMessage(Message)
     */
    public void onMessage(Message message) {
        
    }

}


Share:

EJB for noobs

Lets say we have a Java program and it has a multiply method which takes 2 arguments,multiply and send back the result. So in runtime we can just pass the references of the 2 varibles and get the result right.

What if the mutliply(arg1, arg2) method is not in the same machine. What if it is in a different machine. So it doesnt make sense to pass the memory references of the variables to a another machine's implementation. So if we have a server like that implemented a functionality like mutliply(arg1, arg2) we can serialize the arguments. Serialization means , you take the values or objects (not the referecnes) and convert that into a byte stream. So when you send serilaize arguments to a server, it can have a deserialize process and get the original messages. Typically for serialization and deseriaization process we have stubs in both ends.

  1. In the client side it is called client stub
  2. In the sever side it is called server skeleton
So how do we know which server to pass serialize messages and which server to call. That is when a registry comes in to play. So that is basic scenario in Java-RMI. Its all about talking with different JVMs. J2EE and EJB are also built up on this very same concepts.






Java bean : object or program that can handle business logic

Enterprise Java bean (EJB): Special type of Java bean that can handle business logic. Or a Java bean that is upto J2EE specifications.

  • EJBs properties are private. So need getters and setters.
  • Should have a no argument constructor
  • Should implement Serializeable API (because we can pass references across JVMs)

A typical EJB system/J2EE server environment  is composed of 3 parts.
  • Component
  • Container
  • Object and remote interface

Component 

A program/object that has functionality of an EJB. There are 2 types of EJB components.
  • Session beans(statefull, statlesss, singleton)
  • Message driven beans

Session beans

Clients can invoke session beans. It stores local data. So no persistancy.
  • Statefull session beans - Unique connection between client and session bean. When the connection is lost session is over.
  • Statelss session beans - Any client can invoke stateless session bean
  • Singleton session bean - One bean for an application. 

Message driven beans

These bean are invoked on special events. So according to events from external entities, they can react. Because not every action is to completed synchronously. For some action you can queue it up and execute when the server can.



Share:

Sorting algorithms 4 - Quick sort

Like merge sort, quick sort is also better than bubble,insertion and selection. Quick sort also uses divide and conqueror approach like merge sort. The basic idea behind in quick sort is that divide array using a pivot element and sort the sub arrays. Unlike merge sort, quick sort is memory wise efficient.

Process

  • In step  you have the original unsorted array.
  • In step 2 select a pivot element. It can be any element in the array, most probably from somewhere middle. But in this case we'll use the last element.
  • Now reorganize the array such that values less than pivot is in the left side and values greater than pivot are in the right side.
  • Now if you just forget about the pivot , what you have is 2 unorderes sub arrays. So you have the same problem in the step 2. So you can now use recursively do the same stpes until you have a one element. Because when you have one element it is also sorted.
  • If you do this until there are no sub arrays left, that means you have a sorted array.

Quick sort - Java implementation

 
public static void quickSort(int[] a, int start,  int end)
{
  if(start < end) {
  
  int pIndex = partition (a, start, end);
  
  quickSort(a, start, pIndex- 1);
  quickSort(a, pIndex+1, end);
  }
 }

 private static int partition(int[] a, int start, int end) {
  //Pivot can be any index.
  // In this case we choose it as the final element
  int pivot = a[end];
  
  int partitionIndex = start;
  
  for(int i = start ; i<=end -1; i++)
  {
   if(a[i] <= pivot){
    int temp = a[i];
    a[i]=a[partitionIndex];
    a[partitionIndex] = temp;
    
    partitionIndex = partitionIndex + 1;
   }
   
  }
  
  int temp = a[partitionIndex];
  a[partitionIndex]=a[end];
  a[end] = temp;
  
  return partitionIndex;
  
  
 }
Share:

Sorting algorithms 4 - Merge sort

Merge sort is faster and efficient than bubble,insertion and selection sorts. But it is not efficient than quick and shell sorts. Time wise merge sort is efficient but this comes with a penalty. That is we need more additional space for merge sort. The basic of merge sort is partition the array in to smaller pieces using recursion and merge them so that you will have a sorted array.


Process

  • Choose a pivot element to partition. Typically middle element of the array is better.
  • Create 2 sub arrays left and right. Size of left and right should be 0 to middle and middle to original array element size.
  • Fill left and right sub arrays from the original array.
  • Recursively do these steps until you have sub arrays of singe element. Which means the base case for recursion is sub array elements should not be less than 1.  
  • When you have single elements you can start merging them to get a sorted array.Partitioning until single elements happens because single elements are already sorted.
  • Now we can compare elements from left array and right array.
  • Until left array elements or right array elements are over, compare them and insert the least element to the array. 
  • When one array is over you can add remaining arrays elements to the sorted array in a sorted order.
  • Tada ! you have a sorted array.


 public void mergeSort(int[] a) {
  int n = a.length;

  // Base case for partitioning
  // Array with single element is already sorted
  if (n == 1)
   return;

  int middle = n / 2;
  // Create sub arrays
  int[] left = new int[middle];
  int[] right = new int[n - middle];

  // Fill sub arrays
  for (int i = 0; i < middle; i++) {
   left[i] = a[i];
  }
  for (int i = middle; i < n; i++) {
   right[i - middle] = a[i];
  }

  // recursively partition until 1 element is there
  mergeSort(left);
  mergeSort(right);

  // Merge sub arrays
  Merge(left, right, a);

 }

 public void Merge(int[] left, int[] right, int[] a) {

  int leftArrItems = left.length;
  int rightArrItems = right.length;

  // i for left array looping
  // j for right array looping
  // k for a array looping
  int i = 0;
  int j = 0;
  int k = 0;

  while (i < leftArrItems && j < rightArrItems) {

   // Decides from what sub array to pick to fill final array
   if (left[i] < right[j]) {
    a[k++] = left[i++];
   } else {
    a[k++] = right[j++];
   }
  }

  // Just in case if any sub array is left over
  // with additional elements
  while (i < leftArrItems) {
   a[k++] = left[i++];
  }
  while (j < rightArrItems) {
   a[k++] = right[j++];
  }

 }

Share:

Sorting algorithms 3 - Insertion sort

Just like bubble and selection sorts, insertion sort is also a simple yet inefficient sorting algorithm on large data sets.


Process

  • Lets take a hypothetical moment where the unsorted array we want to sort is partially sorted.
  • So the left part is sorted in ascending order and right part is not yet sorted.
  • we will mark first element in the unsorted part as out. That indirectly says that the last element in sorted portion we can mark as in-1, if we say in = out
  • So now,we can take in-1 th element and move sorted portion until we find a place to put in-1.
  • When that happens, unsorted portion decreases by 1. That means out decrements by 1 and sorted portion increases by  1 position.
  • The data structure is sorted when out goes from 1 to length of the data structure.

// Insertion sort implementation
 public int[] insertionSort(int[] array) {

  for (int out = 1; out < array.length; out++) {
   int in = out;
   int temp = array[out];
   
   while (in>0 && temp<= array[in-1]){
    //move sorted portion to have some space to array[in-1]
    array[in] = array[in-1];
    in --;
   }
   
   array[in] = temp;
  }

  return array;
 }
Share:

Sorting algorithms 2 - Selection sort

Selection sort is also like bubble sort. It uses another different approach for sorting comparing to bubble sort. But when it comes to sort large volumes of data it is inefficient yet good,easy,adaptive for small volume of data.


Process

  • Lets say we want to sort an unsorted array in ascending order. Meaning largest data on right hand corner.
  • Lest select in th element as the minimum
  • Now from in+1 th element to out element I'm searching a value that is lower than the selected minimum value.
  • If I found a such value that means there is a minimum value than our selected minimum value.
  • So I will swap the initially selected minimum and newly found minimum,
  • Now the minimum is on the left.
  • Now we can worry about the array starting from in+1 to out.
  • Select minimum as in+1 and repeat the above procedure until in gets to out.

 // Selection sort implementation
  public int[] selectionSort(int[] array)
  {
   
   int out = array.length - 1;
   for (int in = 0; in < out; in++) {
   
    int min = in;
    
    for (int j = in+1; j < out + 1; j++) {
    
     if (array[min] > array[j]) {
      
      min = j;
    }
   }
    
    int temp = array[in];
    array[in] = array[min];
    array[min] = temp;
  }
   
   return array;
  }
Share:

Sorting algorithms 1 - Bubble Sort

Bubble sort is one of the simplest and easiest of sorting algorithms available. But bubble sort is has almost no practical usage because it is inefficient to sort large volumes of data. Then again bubble sort is good easy solution for simple low volumes of data.



Process

  • Lets say we want an array of ascending order. Meaning largest element in the right corner.
  • First take first element. That is [in] th element according to the figure above.
  • Then compare[in] and [in + 1] th element.
  • If in > in+1, we have swap these two. Because we want to move the largest element of this array to the right hand corner.
  • We have to do this untill, in=0 to in<out. When this first pass is over, largest element is on out.
  • So now we have to take care of the array, starting from in=0 to out-1.
  • So in each pass next largest value goes to right hand corner and out decrements by 1.
  • When out reaches 1, that means the array is sorted.

 /*
  * Bubble sort implementation
  * 
  * Input: unsorted array
  * Output: sorted array
  * 
  * 
  * */
  
  public int[] bubbleSort(int[] array)
  {
   
   for (int out = array.length - 1 ; out > 1; out --) {
    
    for (int i = 0; i < out; i++) {
     
     if (array[i] > array[i+1])
     {
      //swap
      int temp  = array[i];
      array[i] = array[i+1];
      array[i+1] = temp;
     }
    }
   }
   
   return array;
   
  }





Share: