Sunday, July 26, 2015

Why EJB (3+)

I have heard people mentioning, why do you need EJBs; my project is great without them. In early days, I too wasn't very convinced. What value it adds ? Can't we leave without EJBs ?

The answer to most of such questions would be; may be!

It's not that you can't implement a distributed application without EJBs. I have worked on couple of quite successful distributed applications which didn't use EJB at all. For that matter, there is no framework/technology which is must in a given situation. There are always few alternatives, but the question is what's the cost or advantages for making a particular choice?

Let's try to understand EJB and other server side Java components:

Where it fits

EJBs runs inside EJB container (of application server) for abstracting your business logic. Below diagram shows different server side components and their relationship with EJB (just shown some of them). When EJB is not there the line gets blurred and the business logic is spread across servlet and other middle layer components like JPA, JDBC, JMS etc.





Why do we need it ?

Business logic shouldn't be performed by web interface component and similarly by persistence layer as well. Web-interface should specialize in handling http request and delegating it appropriately to business component and persistence layer should focus on CRUD operations.  If your business logic is spread across multiple component, it's not easy to manage it. You are violating loose coupling and separation of concern design principles (not following MVC architectural pattern).

If your business logic is light-weight then you might go on with this approach. But are you sure, that it's going to remain light weight forever? Change is inevitable!

When you have a truly distributed application with multiple server side components and business logic is not so trivial, you will feel the need to bring in an specialized component sooner or later. EJB integrates quite easily with other server side components like JPA (for persistence services), JTA (for transaction services), JMS (for providing messaging services), JNDI (for providing directory services) etc. EJB helps scaling out your application.


Arguments given here are generic, but have written this article keeping in mind features and power of EJB 3+.  Development with EJB 3+ is quite simple - no complex configuration in XML, simple POJO class, uses annotation, and makes development quite a breeze. 

---
happy learning !

Saturday, July 25, 2015

Insertion Sort

Insertion sort is one of the most fundamental comparison based stable sorting algorithm. It is also known as playing card sort. It is based on a fundamental principle that a single element array is already sorted.  A two element array requires single comparison to sort it. A three element array can be visualized as two sub arrays (first with 2 elements and second with one element). So in each iteration, a new value is added to an already sorted sublist. 

a1 = {101}   // already sorted
a2 = {101, 2} // can visualize it as, add 2 to a already sorted sub-array having 101
       {2, 101} // one comparison required to put 2 in proper place
a3 = {101, 2, 5} // a new number added to a2
        {2, 101, 5}
        {2, 5, 101}  // put 5 in proper place

To visualize how it works, check out animation on wikipedia.

Java Implementation


/**
 * Insertion sort implementation
 * 
 * @author Siddheshwar
 *
 */
public class InsertionSort {
 /**
  * Insertion sort in ascending order
  * 
  * @param arr
  * @return arr
  */
 public int[] sort(int[] arr) {
  int tmp = 0;
  for (int i = 1; i < arr.length; i++) {
   for (int j = i; j > 0 && arr[j] < arr[j - 1]; j--) {
    tmp = arr[j];
    arr[j] = arr[j - 1];
    arr[j - 1] = tmp;
   }
   print(arr);
  }
  return arr;
 }

 // print current state of array
 private void print(int[] arr) {
  System.out.println();
  for (int i = 0; i < arr.length; i++) {
   System.out.print(arr[i] + "  ");
  }
 }

 public static void main(String[] args) {
  int[] arr = { 12, 11, 13, 5, 6 };
  InsertionSort is = new InsertionSort();
  arr = is.sort(arr);
  // is.print(arr);
 }
}

Output:
11  12  13  5  6  
11  12  13  5  6  
5  11  12  13  6  
5  6  11  12  13 

Performs ideal when array is nearly sorted or size is small. It can also be used as base sorting algorithm in recursive divide and conquer quick sort and merge sort algorithms.

Important Points

  • If the array is already sorted, swapping will never be performed and hence time complexity will be O(n). Adaptive sorting algorithm. 
  • Average and worst case time complexity is O(n^2). Space complexity is O(1)
  • Worst performance when array is reverse sorted. 
  • Not ideal approach if data is random.
  • In the best case (when already sorted), all the elements are in proper place so it takes linear time. 
  • In-efficient for value based data with large memory footprint as amount of memory shift/swap will be high. Performs good when sorting on pointer based data. 
keep coding !

Monday, July 20, 2015

What is Java EE container

For Java SE (or J2SE) applications JVM provides runtime environment, but the moment you switch to Java EE (or earlier known J2EE), runtime environment is provided by web or application servers.

JVM executes/runs Java applications and also provides some of the runtime services like lifecycle management for objects and API support etc. Life is not so rosy in the distributed environment and that's why we have servers for specific jobs. These servers basically fall into two categories, application servers like JBoss(Wildfly) and Glassfish and web servers like Tomcat and Jetty. These servers are also referred to as containers (in a more technical sense). So what are containers?

Java EE Container

Java EE containers are runtime environments for Java Enterprise Edition applications. As containers are implemented on top of JVM, they provide all services provided by JVM (to Java SE applications) and along with that they also provide services specific to the distributed environment. Java EE containers refer to two different types of containers known as Web/Servlet container and EJB container. They are classified in terms of what technologies they support. Let's go through both these containers in more detail:

Web Container:
Web containers run web applications which use Servlet, JSP and JSF pages and respond to HTTP calls from HTTP clients like browsers, mobile devices or other Java (SE or EE) applications. It can also host RESTful and SOAP web services. Now a subset of EJB 3.1 (added in Java EE 6), known as EJB lite can also be deployed in web containers (in fact EJB lite can also run on JVM). So, it intercepts HTTP(S) request from the client and then identifies, instantiates, initializes appropriate servlet/service endpoint; and then returns back the appropriate HTML page or response in JSON/XML/Text format. 

EJB Container:
EJB containers run enterprise applications made up of Enterprise Java Beans within the Application server. It abstracts business logic of your Java EE application and usually takes request from Servlets,  web services,  queue or other application servers. And just like servlet containers, EJB containers manages lifecycle of EJBs and provides services like transaction management, security, concurrency, naming services or ability to be invoked asynchronously.

Please note that Java EE compliant application servers support Servlet containers along with EJB containers; you can run full stack Java Enterprise Edition application. I have come across situations where people (loosely) refer to Applications servers as EJB containers. 
In the application server, web container and EJB container both share the same JVM instance. 

---

happy learning !!!

Monday, July 13, 2015

Ant Properties

If you are a Java programmer, you should be familiar with properties which are used to maintain the list of key-value pairs. Ant properties too store key-value pairs.

Ant properties play an important role during the build as the placeholder for key/value pairs. To successfully run Ant build, some of the useful properties must be set first and then read it during appropriate targets. So you set it once and can use it multiple times during the build.  You might need build number, app name etc during multiple targets (during generating jar, war or ear). Let's explore it:

Create Properties

Ant provides property task to create properties. Depending on the scope we can create them at the top of the build.xml file or in the specific target.

<!-- simple key value pairs -->
<property name="build.debug" value="true"/>
<property name="blog.name" value="geekrai"/>

<!-- location attribute converts relative path to an absolute path-->
<property name="release.dir" location="../release" />

In the second case, release.dir property stores platform agnostic path of the release directory.  So, depending on underlying OS (Window/Unix/Mac) it will appropriately store the release directory path.

Reading Properties

Property value can be read by surrounding it with ${}.


<echo message="user.name = ${user.name}"/>
<echo>release.dir = ${release.dir}</echo>



So, quite logically the property needs to be defined first before reading its value. Here, Ant does an incredible job of providing some pre-populated in-build properties. So you can just use them without bothering for declaration.

Common inbuilt-properties
ant.file: Absolute path of build file
ant.home: Absolute path of Ant installation directory
ant.java.version: Ant detected JVM version
basedir: Absolute path of projects home directory
user.name: Username

This list is quite big, if you want to see the full list provided by Ant, use below target ($ant printAll).

<target name="printAll">
    <echoproperties />
</target>

Loading from a Properties file

Properties by default are put in the build file, but you can organize them into a separate properties file as well. This helps in easy management of properties, especially if your build file is quite huge. So to achieve this, we can create build.properties in the root directory of the project.

#sample property from build.property file
app.name=AntDemo
build.debug=true
#end of file

It can be loaded using Ant property task as shown below:
<property file="build.properties">

But, do keep in mind that properties are loaded as simple string values so if you set relative file path, it stays as it (unlike location). Also, Ant uses java.util.Properites class to load properties so you should do proper escaping for backslash (\ into \\).


Setting from Command Line

Until now, we discussed about setting properties in build file or separate file. Ant also allows to dynamically set the value of a property. If the value is already getting assigned in build file, then it will get overridden with this approach. Remember, the first assignment rules!

$ant -D<<propertyName=value>> <<target>>
$ant -Dapp.name=dummy build

So in above example, app.name value will become dummy. This always takes precedence. The reason for this is that, properties are immutable so once set it will not change during the course of that build process. 


---
keep coding !!!

Sunday, July 12, 2015

Ant Data Types

As users of Ant build systems, we deal mostly with targets ($ant target). Targets, use multiple tasks(or actions) to achieve the goal. Echoing something to console, making directory, compiling source file are some of the commonly occurring tasks in Ant build. Task requires some inputs like a list of files, list of jars, known as datatypes in Ant world. 

Ant datatype store piece of information during the build, for example, list of files, to be created, compiled, deleted etc.  The datatypes can be declared inside a task or can be declared outside and then passed to task as a parameter. The second approach allows you to share the datatype in multiple tasks with the reference.  To stress on the concepts, I have abstracted some of the datatypes into simple targets:

File Set

Fileset datatype can abstract list of files to be compiled, copied, detected, tested etc. This datatype basically refers to set of files contained in a given directory (including files in subdirectories). Let's take a simple example of copying files from one directory to another directory:

//build.xml

<?xml version="1.0"?>
<project name="AntDemo">
 <fileset id="source.fileset" dir="src"/>

 <target name="copy1">
  <copy todir="backup1">
    <fileset refid="source.fileset"/>
  </copy>
 </target>
 
 <target name="copy2">
  <copy todir="backup2">
    <fileset dir="src"/>
  </copy>
 </target>
 
</project>

So, there are two approaches to copy files. In the first approach (copy1), we have declared a reference to the list of all Java files inside src directory. This is helpful if you want to do this activity multiple times. The second approach (copy2) is more traditional and provides all details inside the same element. For the first approach to work make sure that fileset was defined earlier.

$ant copy1
$ant copy2

Both targets perform the same operation. i.e. copy all files from src directory and copy them over to the backup directory.

Pattern Set

In above example, both targets will copy all files from the src directory. Now, what if you want to copy, say, only java files. Pattern set filters files from the given directory.

//build.xml

<?xml version="1.0"?>
<project name="AntDemo">
 <target name="copyJava">
  <delete dir="backup"/>
  <copy todir="backup">
    <fileset dir="src" includes="**/*.java"/>
  </copy>
 </target>
 
 <target name="copyJava2">
  <delete dir="backup"/>
  <copy todir="backup">
    <fileset dir="src">
     <include name="**/*.java"/>
    </fileset>
  </copy>
 </target>
 
 <patternset id="java.files.only">
     <include name="**/*.java"/>
     <exclude name="**/*.js"/>
 </patternset>
 
 <target name="copyJavaOnly">
  <delete dir="backup"/>
  <copy todir="backup">
    <fileset dir="src">
      <patternset refid="java.files.only"/>
    </fileset>
  </copy>
 </target> 
</project>

Above build.xml shows multiple ways you can apply filter to fileset.

**/*.java - matches all the java files in directory and sub-directories.
*.java - matches only java files in the given directory

File List

This data type is similar to fileset and it's useful when you need to order set of files. Also filelist can be applied on non-existent files.  Shown below a task which creates files.

 <touch>
  <filelist dir="." files="1.txt,2.txt">
   <file name="web.xml" />
   <file name="*.txt" />
  </filelist>
 </touch>

*.txt will just create a single file with name, *.txt.


Filter Set

During the build process, we might need to dynamically fill in values of the file with today's date or build number. Ant has a specific data type of handle this scenerio, filterset.

Below task copies, version.txt from build directory to dist directory and replaces the token @DATE with today's date.

 <copy file="${build.dir}/version.txt" toFile="${dist.dir}/version.txt">
  <filterset>
   <filter token="DATE" value="${TODAY}" />
  </filterset>
 </copy>

More examples, here.


Path

Path data type in Ant is used to represent Java CLASSPATH or the PATH environment variable of Unix/Windows systems. It's an ordered list of elements where each element can be either a file or directory.  We can separate individual elements with either color or semicolon (: or ;). Also for directories, we can choose either Unix style (forward slash, /) or Windows style (backward slash, \). Ant handles it properly depending on the type of system.

If path structure consists of a single path or location or with multiple files:
<path location="lib/junit.jar" />

<path>
 <pathelement path="build/classes;lib/junit.jar" />
</path>



Can be used below approach if path consists of set of files:
<path>
  <fileset dir="lib">
    <include name="*.jar"/>
  </fileset>
</path>


---
keep coding !!!


Saturday, July 4, 2015

Invoking Java class through Ant

Ant is a powerful tool which can run Java programs as well as part of your build process. This might be helpful in running a utility class during the build. It can also be handy to do smoke testing by running some of the test classes during the build. Literary you can perform any operation during the build if you are able to call a Java class.

This post, I will discuss creating a dedicated target to run a Java class.

Create Java Project

Let's create a sample Java project with a single class file with the main method so that it can be invoked from an external tool (i.e. Ant).




/**
 * Sample Java class
 * @author Siddheshwar
 *
 */
public class RunMe{
 public static void main(String[] args){
     System.out.println("Inside main method of RunMe");
            if(args.length !=0 ){
              System.out.println("you passed argument="+args[0]);
            }  
       }
} 

build.xml

<?xml version="1.0"?>
<project name="AntSample" default="compile">
 <!--Declare common properties  -->
 <property name="src.dir"     value="src"/>
 <property name="build.dir"   value="build"/>
 <property name="RunMe-class"  value="RunMe"/>
 <property name="classes.dir" value="${build.dir}/classes"/>

 <!-- init target to clean up existing build directory -->
 <target name="clean">
  <delete dir="${build.dir}"/>
 </target>

 <!--Before running a Java class; that class should be compiled   -->
 <target name="compile" depends="clean">
  <echo>compilation started -</echo>
  <mkdir dir="${classes.dir}"/>
  <javac srcdir="src" destdir="build/classes" />
  <echo>compilation complete!</echo>
 </target>

 <!--Execute the java class   -->
 <target name="execute" depends="compile">
  <java classname="RunMe" classpath="build/classes">
   <arg value="hello" />
   <arg file="." />
  </java>
 </target>

 <!-- abstracts clean and execute target -->
 <target name="main" depends="clean,execute"/>
</project>


Executing Java class

In build.xml file execute target is declared to run the Java class. Before running the class it should have been compiled and that's the reason for adding dependency on compile target. This way when we run execute target, it will run compile first. Target, execute provides all information required for running a program. It provides name of the class (i.e. className) as well as path of class through classpath. It also passes an argument to the main method having value hello. 
The last argument file, tells Ant to resolve that attribute to an absolute file location. 

That's it; you are done!

Now let's run the class: 
I have given below multiple options for running the Java program (Ant Cheat Sheet), you can call any of them:

$ant execute
or
$ant main
or
$ant compile execute
or
$ant clean compile execute

Response

$ant main
Buildfile: /Users/siddheshwar/Documents/gitRepo/AntSample/build.xml

clean:
   [delete] Deleting directory /Users/siddheshwar/Documents/gitRepo/AntSample/build

compile:
     [echo] compilation started -
    [mkdir] Created dir: /Users/siddheshwar/Documents/gitRepo/AntSample/build/classes
    [javac] /Users/siddheshwar/Documents/gitRepo/AntSample/build.xml:18: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 1 source file to /Users/siddheshwar/Documents/gitRepo/AntSample/build/classes
     [echo] compilation complete!

execute:
     [java] Inside main method of RunMe
     [java] you passed argument=hello

main:

BUILD SUCCESSFUL
Total time: 0 seconds

--

Keep coding!

Thursday, July 2, 2015

Manipulating Java Archives

Java bundles deployable files in formats like jar, war and ear. These files are basically zipped files which is understood by Java environment or Java EE compliant servers. Various tools available to be used with zip files can be used with these Java archived files as well. This post, I will be covering how to manipulate these file through command prompt. We can use jar utility to manipulate Java archives files. 

Java Archived Formats = jar, war, ear 

In the below examples, I have used only one file format (mostly jar) but you can certainly run the command on with other formats (war and ear) as well. 

Listing Content

jar command can be used to list the content of Java archives. Below command shows the list of all files on the console.

$jar tvf <<file.jar | file.war | file.ear>>
$jar tvf gson-2.2.1.jar

t - > list content of archive
v -> in verbose mode
f -> file name specified

The response of the above command can be pretty huge, so if you looking for any specific file use grep to filter that specific file. 

$jar tvf gson-2.2.1.jar | grep Gson.class
18281 Fri May 11 11:48:48 IST 2012 com/google/gson/Gson.class

Extracting Content

The contents of the archived file can be extracted with the x (i.e. extract) option. 

$jar xvf gson-2.2.1.jar

Above command will extract all files from the jar. In some cases you might just be interested in a particular file from the jar (or war or ear). This can be achieved by giving file name as shown below:

$jar xvf gson-2.2.1.jar com/google/gson/Gson.class
-rw-r--r--  1 Siddheshwar  staff  189617 Jul  2 16:54 gson-2.2.1.jar
drwxr-xr-x  3 Siddheshwar  staff     102 Jul  2 16:55 com


So above command creates a directory with name com. If you follow the proper path com/google/gson you will see just single file. One alternative to above approach is that unarchive the whole jar file but grep for the specific file which you are looking for. If it's present, the console will show it as output in the next line (as shown below).

$jar xvf gson-2.2.1.jar | grep Gson.class
inflated: com/google/gson/Gson.class



References