Monday, December 17, 2012

Checking out what is new with Servlet 3.0

With the JEE6 specification hitting the market, some major changes have taken place with respect to how you would approach developing applications in the enterprise application world. In this article i would be touching upon a few changes that were done with respect to web application development.

First things first, say good bye to the web.xml deployment descriptor (at least for parts of it). Well its not like it is deprecated, but with the rise of the usage of annotations and their usage, the new specification allows us to define our configuration using annotations, though some thing such as welcome file lists, context params etc will still need to go inside your web.xml . Annotations available for use are;


  • @WebServlet
  • @WebFilter
  • @WebInitParam
  • @WebListener
  • @MultipartConfig
In this article i would be checking out the @WebServilet and @WebFilter annotations. Let us see how we would usually map a servlet in the web.xml era;





    <servlet>
        <servlet-name>myservlet</servlet-name>
        <servlet-class>com.example.MyServlet</servlet-class>
    </servlet>
 
 <servlet-mapping>
  <servlet-name>myservlet</servlet-name>
  <url-pattern>/hello</url-pattern>
 </servlet-mapping>

With the Servlet 3.0 spec, now configuring a Servlet is as easy as annotating a class that extends HttpServlet. Lets see how that looks like;


@WebServlet("/student")
public class StudentServlet extends HttpServlet{

 /**
  * 
  */
 private static final long serialVersionUID = 2276157893425171437L;

 @Override
 protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1)
   throws ServletException, IOException {
  StringBuilder response = new StringBuilder(500);
  response.append("<html><body>").append("Registered Student : ").append(arg0.getParameter("txtName")).append("</body></html>");
  arg1.getOutputStream().write(response.toString().getBytes());
  arg1.getOutputStream().flush();
  arg1.getOutputStream().close();
 }
}

All you need is the @WebServlet annotation. In order for this to work, the class should reside either in the WEB-INF/classes folder or within a jar residing in the WEB-INF/lib folder. Next up lets see how we would configure a filter with annotations.


package com.blog.example.servlettest;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter("/student")
public class StudentFilter implements Filter{

 @Override
 public void destroy() {
 }

 @Override
 public void doFilter(ServletRequest arg0, ServletResponse arg1,
   FilterChain arg2) throws IOException, ServletException {
  
  if(arg0.getParameter("txtName")==null || arg0.getParameter("txtName").isEmpty())
  {
   arg1.getWriter().append("Invalid name supplied");
   arg1.getWriter().flush();
   arg1.getWriter().close(); 
  }
  else
  {
   arg2.doFilter(arg0, arg1);
  }
 }

 @Override
 public void init(FilterConfig arg0) throws ServletException {
  // TODO Auto-generated method stub
  
 }

}


Again very easy. Just a mere annotation to notify it as a filter. Note that here we implement the Filter interface. The value or the urlPatterns should be available. Using both is illegal as per the specification.

In the coming weeks i will cover the other new annotations available with JEE6 and wrap up with a comprehensive example using them together. If JEE6 will replace Spring framework or not is not a question by itself, but i believe we would be seeing some fierce competition between the two. The annotations vs xml debate is more or less resolved with people with preference for each holding their own grounds. I believe a little bit from both worlds would be beneficial for an application.

You can download and run a sample example which i have uploaded here. If you are using JBoss-AS7 all you need to do is run the application server on standalone mode and do a mvn package jboss-as:deploy and point the browser to http://localhost:{port}/servlet3.0.

That is it for today. Thank you for reading and if you have any comments or suggestions for improvement, please do leave by a comment.

Have a good day all!!

Thursday, December 13, 2012

Configuring syntax highlighting for your blog

Thought i would put up a quick reference guide on how to configure syntax highlighting for people trying to figure it out for the first time. It is not that hard anyways. Let me guide you step by step. First of all just before the close head (</head>) tag insert the following;


<style type='text/css'>
.dp-highlighter
{
 font-family: &quot;Consolas&quot;, &quot;Courier New&quot;, Courier, mono, serif;
 font-size: 12px;
 background-color: #E7E5DC;
 width: 99%;
 overflow: auto;
 margin: 18px 0 18px 0 !important;
 padding-top: 1px; /* adds a little border on top when controls are hidden */
}

/* clear styles */
.dp-highlighter ol,
.dp-highlighter ol li,
.dp-highlighter ol li span 
{
 margin: 0;
 padding: 0;
 border: none;
}

.dp-highlighter a,
.dp-highlighter a:hover
{
 background: none;
 border: none;
 padding: 0;
 margin: 0;
}

.dp-highlighter .bar
{
 padding-left: 45px;
}

.dp-highlighter.collapsed .bar,
.dp-highlighter.nogutter .bar
{
 padding-left: 0px;
}

.dp-highlighter ol
{
 list-style: decimal; /* for ie */
 background-color: #fff;
 margin: 0px 0px 1px 45px !important; /* 1px bottom margin seems to fix occasional Firefox scrolling */
 padding: 0px;
 color: #5C5C5C;
}

.dp-highlighter.nogutter ol,
.dp-highlighter.nogutter ol li
{
 list-style: none !important;
 margin-left: 0px !important;
}

.dp-highlighter ol li,
.dp-highlighter .columns div
{
 list-style: decimal-leading-zero; /* better look for others, override cascade from OL */
 list-style-position: outside !important;
 border-left: 3px solid #6CE26C;
 background-color: #F8F8F8;
 color: #5C5C5C;
 padding: 0 3px 0 10px !important;
 margin: 0 !important;
 line-height: 14px;
}

.dp-highlighter.nogutter ol li,
.dp-highlighter.nogutter .columns div
{
 border: 0;
}

.dp-highlighter .columns
{
 background-color: #F8F8F8;
 color: gray;
 overflow: hidden;
 width: 100%;
}

.dp-highlighter .columns div
{
 padding-bottom: 5px;
}

.dp-highlighter ol li.alt
{
 background-color: #FFF;
 color: inherit;
}

.dp-highlighter ol li span
{
 color: black;
 background-color: inherit;
}

/* Adjust some properties when collapsed */

.dp-highlighter.collapsed ol
{
 margin: 0px;
}

.dp-highlighter.collapsed ol li
{
 display: none;
}

/* Additional modifications when in print-view */

.dp-highlighter.printing
{
 border: none;
}

.dp-highlighter.printing .tools
{
 display: none !important;
}

.dp-highlighter.printing li
{
 display: list-item !important;
}

/* Styles for the tools */

.dp-highlighter .tools
{
 padding: 3px 8px 3px 10px;
 font: 9px Verdana, Geneva, Arial, Helvetica, sans-serif;
 color: silver;
 background-color: #f8f8f8;
 padding-bottom: 10px;
 border-left: 3px solid #6CE26C;
}

.dp-highlighter.nogutter .tools
{
 border-left: 0;
}

.dp-highlighter.collapsed .tools
{
 border-bottom: 0;
}

.dp-highlighter .tools a
{
 font-size: 9px;
 color: #a0a0a0;
 background-color: inherit;
 text-decoration: none;
 margin-right: 10px;
}

.dp-highlighter .tools a:hover
{
 color: red;
 background-color: inherit;
 text-decoration: underline;
}

/* About dialog styles */

.dp-about { background-color: #fff; color: #333; margin: 0px; padding: 0px; }
.dp-about table { width: 100%; height: 100%; font-size: 11px; font-family: Tahoma, Verdana, Arial, sans-serif !important; }
.dp-about td { padding: 10px; vertical-align: top; }
.dp-about .copy { border-bottom: 1px solid #ACA899; height: 95%; }
.dp-about .title { color: red; background-color: inherit; font-weight: bold; }
.dp-about .para { margin: 0 0 4px 0; }
.dp-about .footer { background-color: #ECEADB; color: #333; border-top: 1px solid #fff; text-align: right; }
.dp-about .close { font-size: 11px; font-family: Tahoma, Verdana, Arial, sans-serif !important; background-color: #ECEADB; color: #333; width: 60px; height: 22px; }

/* Language specific styles */

.dp-highlighter .comment, .dp-highlighter .comments { color: #008200; background-color: inherit; }
.dp-highlighter .string { color: blue; background-color: inherit; }
.dp-highlighter .keyword { color: #069; font-weight: bold; background-color: inherit; }
.dp-highlighter .preprocessor { color: gray; background-color: inherit; }

</style>
<!-- Add-in CSS for syntax highlighting -->  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shCore.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCpp.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCSharp.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushCss.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushDelphi.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJava.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushJScript.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPhp.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushPython.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushRuby.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushSql.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushVb.js' type='text/javascript'/>  
<script src='http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/shBrushXml.js' type='text/javascript'/>  

Next up you need to initialize a few javascript functions to make the syntax highlighting work. Therefore insert the following snippet just before the close body (</body>) tag;


<!-- Add-in Script for syntax highlighting -->  
<script language='javascript'>  
dp.SyntaxHighlighter.BloggerMode();  
dp.SyntaxHighlighter.HighlightAll(&#39;code&#39;);  
</script> 
That is it. Afterwards whenever you want to post a code in one of your posts just have your code within pre tag blocks as follows;

<pre class="java" name="code">
//your code goes here
</pre>


Note that before pasting code within the block you need use an html encoder. I usually prefer this html encoder which is an online tool. Also there are many options you can use within the class attribute. More information on the brushes available can be found here.

Happy coding people!!

Friday, November 30, 2012

How to start a thread on JBoss startup

I recently had to initiate a thread to read mails on server start-up. This had to run after the application was deployed since the thread class depended on a few classes of the application. Note that we are running on JBoss 4.2.3 currently, so i am not sure how this works with latest versions of JBoss.

You need to create a folder called deploy.last within your deployment directory (e.g : default configuration). Then we first create a normal interface/implementation as follows;


public interface EmailRetrieverInvokerServiceMBean {

 void start() throws Exception;

 void stop();
}



public class EmailRetrieverInvokerService implements
  EmailRetrieverInvokerServiceMBean {

 public void start() throws Exception {

  
  MailRetriever mailRetriever= new MailRetriever();
  mailRetriever.start();
 }

 public void stop() {
  
            MailRetriever.START_STOP_FLAG = true;

 }
}


Just a normal interface and implementation. Note that the start() method will be called when we deploy the application. The MailRetriever class has an implementation as follows;


public class MailRetriever extends Thread {

   public static boolean START_STOP_FLAG = false;

    @Override
    public void run() {
        
        log.info("MailRetriever started....");

        //Until the flag is not set to true, this thread will keep running
        while (!START_STOP_FLAG) {
            try {
                
                
             
             //Do mail reading

             //Then sleep for a specified time until the next iteration
                Thread.sleep(1000 * 60 * mailPollingDelay);
            } catch (Exception ex) {
                log.error("MailRetriever.run()" + ex.getMessage(), ex);
                //Exception handling and thread respawning should be handled
            }
        }
    }
}


This is the thread that will be started when the start() method of our MBean implementation class is invoked. The thread will continue to run until the boolean flag is set to true. Then to wire it up, you need to specify a jboss-service.xml which should go in the META-INF directory when building your distribution. Let us have a look at what that looks like;


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

<server>
   <mbean code="com.service.EmailRetrieverInvokerService"
   name="com.service:service=EmailRetrieverInvokerService">    
  </mbean>
</server>


Within this xml we define the fully qualified path to our interface class that we defined and give a name where we can access our implementation as a normal MBean definition. If you are using a maven build then all you need to do is create this XML file and put it under src/main/resources/META-INF. This will put it under the META-INF during the distribution creation stage.

As a last step what you need to do is bundle everything up as a service archieve (SAR). You can achieve this using maven as follows;


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.example</groupId>
 <artifactId>mailreader</artifactId>
 <packaging>sar</packaging>
 <version>1.0</version>
 <name>Mail Reader</name>

 <build>
 <finalName>MailReader</finalName>
  <plugins>

   <plugin>
    <groupId>net.sf.maven-sar</groupId>
    <artifactId>maven-sar-plugin</artifactId>
    <version>1.0</version>
    <extensions>true</extensions>
   </plugin>
  </plugins>

 </build>


 <properties>
  <project.build.sourceEncoding>UTF-8
  </project.build.sourceEncoding>
 </properties>


</project>


A service archive will be created for you. Then it is just a matter of copying the SAR file onto your deploy.last which you created within the jboss deployment directory. This will guarantee that the thread will run after all other components are deployed within jboss.

That's it. If you have any queries, comments, suggestions, please leave them which is much apprecaited as always.

Thank you for reading and have a great day!!

Monday, November 26, 2012

How cool is integration testing with Spring+Hibernate

I am guilty of not writing integration testing (At least for database related transactions) up until now. So in order to eradicate the guilt i read up on how one can achieve this with minimal effort during the weekend. Came up with a small example depicting how to achieve this with ease using Spring and Hibernate. With integration testing, you can test your DAO(Data access object) layer without ever having to deploy the application. For me this is a huge plus since now i can even test my criteria's, named queries and the sort without having to run the application.

There is a property in hibernate that allows you to specify an sql script to run when the Session factory is initialized. With this, i can now populate tables with data that required by my DAO layer. The property is as follows;


 <prop key="hibernate.hbm2ddl.import_files">import.sql</prop>

According to the hibernate documentation, you can have many comma separated sql scripts.One gotcha here is that you cannot create tables using the script. Because the schema needs to be created first in order for the script to run. Even if you issue a create table statement within the script, this is ignored when executing the script as i saw it.

Let me first show you the DAO class i am going to test;


 package com.unittest.session.example1.dao;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.unittest.session.example1.domain.Employee;

@Transactional(propagation = Propagation.REQUIRED)
public interface EmployeeDAO {

 public Long createEmployee(Employee emp);
 
 public Employee getEmployeeById(Long id);
}



package com.unittest.session.example1.dao.hibernate;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.unittest.session.example1.dao.EmployeeDAO;
import com.unittest.session.example1.domain.Employee;

public class EmployeeHibernateDAOImpl extends HibernateDaoSupport implements
  EmployeeDAO {

 @Override
 public Long createEmployee(Employee emp) {
  getHibernateTemplate().persist(emp);
  return emp.getEmpId();
 }

 public Employee getEmployeeById(Long id) {
  return getHibernateTemplate().get(Employee.class, id);
 }
}

Nothing major, just a simple DAO with two methods where one is to persist and one is to retrieve. For me to test the retrieval method i need to populate the Employee table with some data. This is where the import sql script which was explained before comes into play. The import.sql file is as follows;



 insert into Employee (empId,emp_name) values (1,'Emp test');

This is just a basic script in which i am inserting one record to the employee table. Note again here that the employee table should be created through the hibernate auto create DDL option in order for the sql script to run. More info can be found here. Also the import.sql script in my instance is within the classpath. This is required in order for it to be picked up to be executed when the Session factory is created.

Next up let us see how easy it is to run integration tests with Spring.


 package com.unittest.session.example1.dao.hibernate;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;

import com.unittest.session.example1.dao.EmployeeDAO;
import com.unittest.session.example1.domain.Employee;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring-context.xml")
@TransactionConfiguration(defaultRollback=true,transactionManager="transactionManager")
public class EmployeeHibernateDAOImplTest {

 @Autowired
 private EmployeeDAO employeeDAO;
 
 @Test
 public void testGetEmployeeById() {
  Employee emp = employeeDAO.getEmployeeById(1L);
  
  assertNotNull(emp);
 }
 
 @Test
 public void testCreateEmployee()
 {
  Employee emp = new Employee();
  emp.setName("Emp123");
  Long key = employeeDAO.createEmployee(emp);
  
  assertEquals(2L, key.longValue());
 }

}


A few things to note here is that you need to instruct to run the test within a Spring context. We use the SpringJUnit4ClassRunner for this. Also the transction attribute is set to defaultRollback=true. Note that with MySQL, for this to work, your tables must have the InnoDB engine set as the MyISAM engine does not support transactions.

And finally i present the spring configuration which wires everything up;


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


 <context:component-scan base-package="com.unittest.session.example1" />
 <context:annotation-config />

 <tx:annotation-driven />

 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="packagesToScan">
   <list>
    <value>com.unittest.session.example1.**.*</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
    <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/hbmex1</prop>
    <prop key="hibernate.connection.username">root</prop>
    <prop key="hibernate.connection.password">password</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <!-- -->
    <prop key="hibernate.hbm2ddl.auto">create</prop>
    <prop key="hibernate.hbm2ddl.import_files">import.sql</prop>
   </props>
  </property>
 </bean>

 <bean id="empDAO"
  class="com.unittest.session.example1.dao.hibernate.EmployeeHibernateDAOImpl">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>

</beans>

That is about it. Personally i would much rather use a more light weight in-memory database such as hsqldb in order to run my integration tests.

Here is the eclipse project for anyone who would like to run the program and try it out.


Wednesday, October 10, 2012

Enter the DROID World!!

Well quite frankly i'm late to the game, but here i am, getting my hands dirty(or wet or whatever you might call it) in the world of android. This post will focus on how to set up the android SDK, setting up ADT for eclipse as well as an introduction to the structure of a typical android project using an example. Lets get going (said in a robotic voice of course)...

First of all you need the Android SDK to get going. Download the relevant version for your platform. Currently it supoprts Windows, Linux and Mac. All right, got it done? Awesome, lets see the minimum you need to get started. Note that when you run the installer you will be presented with the following screen;

Android SDK Manager
The rows i have marked with an arrow are the minimum elements you need to download in order to get started. Of course here i have presented my SDK manager in which i have installed almost everything. But that takes too much of time, and i know all of you do not have much time to spare. So just download the marked elements and lets get this show on the road!!!!

Got everything installed? Great, now lets set up our eclipse platform to start creating awesome android applications. Note that you require Eclipse 3.6 or higher to get the ADT ( Android Development Tools) plugin to work.

Go to install new software and add the location of the ADT plugin which is http://dl-ssl.google.com/android/eclipse . You only need to download the Developer tools from the ADT plugin because you will only need the NDK in a few instances. The NDK is the native development kit which allows you to program at a lower level using C language specifics. This post will only focus on the Android SDK.

So once you get that done you are ready to roll my friend. Before that i would like to mention a few things that are available to you after installing the Android SDK. You will have the SDK Manager and the AVD manager. The SDK manager will show any tools or APIs you need to download and you can use this tool to upgrade you environment as and when you need. We will get to the AVD manager when we look at the sample application.

In Eclipse, go to New->Other->Android->Android Application Project and follow the steps. Note that in the first screen you will have an option to specify the minimum required SDK. This signifies the minimum android SDK your application needs to run. Select the option "Create Activity" and select the blank activity option. Give it a name and finish off the application creation process.

Now you will be presented with a structure as follows;

Lets take a look at what each folder is for.

assets : any property file, databases, text files or the sort which you want to bundle up with your application can be put here. This can have its own folder hierarchy within it self and you can read those files in the usual way you do file reading in java.

bin : contains the various files built by the ADT plugin. It will contain the .apk(Android application package file)

gen : this folder contains mainly two files that are compiler generated. Which are R.java & BuildConfig.java. I will explain more about he R.java in a bit. It is best not to edit these files as these are anyway generated on each build.

libs : Contains the android jar that exposes the android APIs required for development. Note that in our application it uses the android-support-v4.jar which is the support version library that allows you to use newer APIs whilst having support for older Android Operating systems.

res : this folder contains all the resources required by your application such as images etc. You can categorize according to various screen resolutions, languages and OS versions. The layout folder will contain the XML file that allows you to define your UI element specific to your activity. The values folder allows you to define language entries in such a way we use .properties files in normal java applications to support different languages. More information can be found here.

src : contains the source files of your project.

AndroidManifest.xml :  The manifest will define the name of the application, icon to be displayed, the various activities used, Permissions required etc. The version code is set to "1" initially. This code is used to determine whether your application has an upgrade available or not. Best practice is to increment the value on each release.

Within the manifest you can see an entry such as android.intent.action.MAIN. This signifies that the activity we just created is the main entry point of the application ( such as the main method in a java program).

R.java : This file is automatically generated and it is recommended that you do not change this file manually because anyway when you do any changes in your project, ADT will generate this file. This file provides access to the resources in your application in a programmatic way so that you can access your resources in a unified manner.


Let us open the blank activity that we just created. Ok the app here does not do much. But i just wanted to introduce the various elements that make up an android application and to jump start development. Within this sample what i show is how to call another activity from your main activity.

Let us first see the xml file pertaining to my main activity.


 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="107dp"
        android:layout_marginTop="134dp"
        android:text="@string/next_activity_btn_name" 
        android:onClick="actClick"/>

</RelativeLayout>

As you can see nothing major here. Just one button which i have defined. The name of the button is defined in the strings.xml in order to make the application localization friendly. Also i have defined an onclick functionality. Let us see how the onClick method is implemented in my main activity;


 
package com.example.droidworld;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class DroidMainActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_droid_main);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_droid_main, menu);
  return true;
 }

 public void actClick(View view) {
  startActivity(new Intent("com.example.droidworld.NextActivity"));
 }
}


You can see that the name of the on click method is the same as what i defined in the XML file. Also the method takes on the View class as a parameter. Within this i use the method startActivity() which enables us to call another activity. Any name can be given here which should correspond to the name given in our application's manifest.xml file. Let us see how we have defined this in our manifest;


 
    <activity
            android:name=".NextActivity"
            android:label="@string/title_activity_next" >
            <intent-filter>
                <action android:name="com.example.droidworld.NextActivity" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>


Within the intent filter tags, the name given for the attribute android:name should correspond with the name given within our Intent() method within the startActivity method call. android.intent.category.DEFAULT  allows another activity to call this activity. You can also get away by not defining intent filters if the activity you are going to call is within your own project. If that is the case then you call the activity directly as such;


 
startActivity(new Intent(this, NextActivity.class));


One thing to note here is that if you want to expose your activity to other applications, then you need to expose it using intent-filters.

That about winds up the introduction to the droid world. I myself am pretty new to this, so if you believe some of what i said in this post is invalid or requires changes, please do leave by a comment which is much appreciated.

You can download the sample project from here. You just need to do a Run->Android Application and you are good to go. Make sure to set up an AVD manager before running the application. The AVD manager creates the emulator on which your application is deployed. Create an instance by going to Windows->AVD Manager. The rest is intuitive so i will not go into detail. If you have any issues please do let me know and i will be glad to help.

I will follow up this post with a few other articles to depict various features available.

Thank you for reading and have a good day. And from words of the Terminator "Hasta la vista "

Cheers!!

Tuesday, October 9, 2012

Locking with a semaphore : An example

Concurrency is one aspect that brings along interesting challenges along with it. If not correctly handled, it brings about race conditions that will baffle people because those issues just pop up from time to time and work flawlessly sometimes.

The Java language gives many ways of handling race conditions when dealing with concurrent threads accessing a common resource. Some include;


  1. Using the volatile keyword
  2. Using classes available in java.util.concurrent and java.util.concurrent.atomic 
  3. Synchronized blocks
  4. Using a Semaphore
Of course there might be many more that i might not be aware of. For today, the example i want to show you all is the one using a Semaphore. This was introduced from JDK 1.5, and provides the developer with the ability to acquire and release locks in a seamless way. Also the example i will be showing is a hypothetical scenario which i used just to depict what can be achieved using a semaphore and therefore please do not look at the intrinsic details of the code :)..

So the scenario as such, there is an in-memory cache holding objects of type "Person". Users can insert and retrieve records using the cache. The issue here is we are going to control concurrent access to our in-memory cache using semaphores. Now i do not want to bore you with more text so lets get to business and show some code;


 
import java.util.concurrent.Semaphore;

/**
 * This class will allow thread to acquire and release locks as required
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class PersonLock {

 /**
  * We do not want multiple lock objects lying around so we make ths class
  * singleton
  */
 private PersonLock() {

 }

 /**
  * Bill Pugh's way of lazy initializing the singleton instance
  * 
  * @author dinuka.arseculeratne
  * 
  */
 private static class SingletonHolder {
  public static final PersonLock INSTANCE = new PersonLock();
 }

 /**
  * Use this method to get a reference to the singleton instance of
  * {@link PersonLock}
  * 
  * @return the singleton instance
  */
 public static PersonLock getInstance() {
  return SingletonHolder.INSTANCE;
 }

 /**
  * In this sample, we allow only one thread at at time to update the cache
  * in order to maintain consistency
  */
 private Semaphore writeLock = new Semaphore(1);

 /**
  * We allow 10 concurrent threads to access the cache at any given time
  */
 private Semaphore readLock = new Semaphore(10);

 public void getWriteLock() throws InterruptedException {
  writeLock.acquire();
 }

 public void releaseWriteLock() {
  writeLock.release();
 }

 public void getReadLock() throws InterruptedException {
  readLock.acquire();
 }

 public void releaseReadLock() {
  readLock.release();
 }
}

This class will handle the process of obtaining and releasing locks required to make our cache thread safe. I have used two separate locks here for reading and writing. The rationale behind this was to allow users to read data though it might be stale at the time of reading.

Note that i have used "ten" here which denotes that ten thread can simultaneously obtain locks and access the cache for read purposes. Next up you can see in the write lock, i have used the "one" which signifies that only one thread can access the cache at a time to put items to it. This is important in order to maintain consistency within the cache. That is, i do not want multiple threads trying to insert items to the map which would result in unpredictable behavior ( at least in some instances). There are mainly two ways by which you can acquire a lock using a semaphore.

 1. acquire() : is a blocking call which waits until the lock is released or the thread is interrupted
2.  tryAcquire() : is a non-blocking call which will return immediately and return true or false signifying whether the lock was obtained or not.

Here i have used the blocking acquire call because i want the thread to wait until the lock is available. Of course this will depend on your use case. You can also define a timeout period in the tryAcquire() method so  that the thread will not wait indefinitely for a lock.

Next up the storage class below shows how i have used the lock class to insert and read data within the cache.




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

/**
 * A mock storage to hold the person objects in a map
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class PersonStorage {

 private Map<Integer, Person> personCache = new HashMap<Integer, Person>();

 private int counter = 0;

 /**
  * This class is made singleton and hence the constructor is made private
  */
 private PersonStorage() {

 }

 /**
  * Bill Pugh's way of lazy initializing the singleton instance
  * 
  * @author dinuka.arseculeratne
  * 
  */
 private static final class SingletonHolder {
  public static final PersonStorage INSTANCE = new PersonStorage();
 }
 
 /**
  * Use this method to get a reference to the singleton instance of
  * {@link PersonStorage}
  * 
  * @return the singleton instance
  */
 public static PersonStorage getInstance()
 {
  return SingletonHolder.INSTANCE;
 }

 /**
  * Inserts the person into the map. Note that we use defensive copying so
  * that even if the client changes the object later on, those changes will
  * not be reflected in the object within the map
  * 
  * @param person
  *            the instance of {@link Person} to be inserted
  * @return the key which signifies the location of the person object
  * @throws InterruptedException
  */
 public int putPerson(Person person) throws InterruptedException {
  
  Person copyPerson = person.copyPerson();
  personCache.put(++counter, copyPerson);
  
  return counter;
 }

 /**
  * Here as well we use defensive copying so that the value of the object
  * reference within the map is not passed in to the calling party.
  * 
  * @param id
  *            the id representing the location of the object within the map
  * @return the instance of the {@link Person} represented by the key passed
  *         in
  * @throws InterruptedException
  */
 public Person retrievePerson(int id) throws InterruptedException {
  PersonLock.getInstance().getReadLock();
  if (!personCache.containsKey(id)) {
   throw new RuntimeException("Key is not found");
  }
  PersonLock.getInstance().releaseReadLock();
  return personCache.get(id).copyPerson();
 }

}

Obviously the code will work without the locks as well, but the issue is that the application will be inconsistent and provide different results at each run. This is not something you want your application to do and hence with locks you guarantee your application works consistently.

And lastly a small test class to show how it will behave; not that in here we obtain the lock before calling the putPerson() method and release the lock within the finally block in order to guarantee the release of the lock.


 
/**
 * A test class to demonstrate the locking at work
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class TestLock {

 public static void main(String[] args) throws InterruptedException {

  Thread t1 = new Thread(new Runnable() {

   @Override
   public void run() {
    
    Person p1 = new Person(1L, "Test1", "XYZ");
    try {
    PersonLock.getInstance().getWriteLock();
PersonStorage.getInstance().putPerson(p1);
    } catch (InterruptedException e) {
     // Exception handling need to be done
     e.printStackTrace();
    }
   finally{
          PersonLock.getInstance().releaseWriteLock();
    }
   }
  });

  Thread t2 = new Thread(new Runnable() {

   @Override
   public void run() {
    
    Person p2 = new Person(2L, "Test123", "ABC");

    try {
     PersonLock.getInstance().getWriteLock();

     PersonStorage.getInstance().putPerson(p2);
    } catch (InterruptedException e) {
     // Exception handling need to be done
    }
 finally{
          PersonLock.getInstance().releaseWriteLock();
    }
    
   }
  });

  t1.start();
  t2.start();

  System.out.println(PersonStorage.getInstance().retrievePerson(2));
 }
}

That concludes my short introduction to using Sempahores to make your code thread safe.For anyone who wants to play around with the code, you can obtain it from here. Try to remove the locks in the Storage class and see how it behaves on each run. You will see possible race conditions taking place.

Appreciate your comments and feedback on the same as always and thank you for reading.

Cheers....

Monday, October 1, 2012

As my journey through IT continue

So recently i just surpassed the 5+ year mark in my career. So i dwelled upon my journey so far and wanted to pen it down ( well key it down in this instance :) ). And this is how my story goes;

Just after Uni, i started working at a start up company specializing in stock trading applications. Even today if someone asked me what was the most challenging thing you have worked on, this company will always be in the top 10. After uni, for a guy looking for a challenging career, this was just what the doctor ordered. Loved every bit of work, and also the people were very courteous and helpful in every way. From the CEO to architect to the tech leads, if you ever needed help with anything, they were always there for me.

Got my very first & only taste of C++ right in this very company. Now that was one heck of a language i must say. Keeps you thinking of every intrinsic detail. Of course looking back it might be overkill comparing with some languages now, but hey for a person just out of Uni, these are interesting stuff. Though i had an apprehensive nature on joining, the people at this company really made it easy for me to settle down.

Thoroughly enjoyed the late nights, trying to figure out why something that seems fine is just not working on production, learnt what true team work is all about.

Then came the time for me to move in pursuit of better opportunities, though my heart up until this date is still with this company because the people there were such fun loving people. The CEO was the key role whom i still look up for. My idol in the local IT sector.

One thing i never stopped was learning. Continuous learning is what keeps your value on par with the industry. If you lose your value, then your not an asset to the company any more. I wont say you should go and learn every technology or language that pops up in the news, but its more or less like engaging in the stock market. If you are not in the know of the stock movements, your bound not to capitalize on the opportunities that might arise in the future.

Few things i have observed on my journey is that often time many people focus just on the money factor. They enter the industry thinking it is a one stop stairway way to wealth. Don't get me wrong, money is important, but entering the software industry with just money being your goal and sole purpose will not take you much far.

What i always believe in is that you should learn from each experience, and with experience and time, money will come. Some people give me this incredulous look when i say that to them. But that reality i have lived is what i tell them. Believing it or not is up to them :).

And then i meet a few rock stars who are solid and sound technical people, but lack communication skills or most often have a very bad case of Asperger syndrome. Often times i see these people rise up early in their career but then be victims of ostracism due to the fact that they just do not understand that at the end of the day, without a team effort, a company will not thrive.

One thing i always believe is humility. This was one of the many gifts i inherited from my father. No matter how far you may go, you should never forget how you got there. A very important saying my father taught me was

                 "Be careful not to step on others' toes on your way up,
                   You do not know who you will meet on your way down ".

Another version goes as;

                  ""Be careful whose toes you step on today because
                  they might be connected to the foot that kicks your ass tomorrow!!"
                  -Brandon Ramos"

 No matter what you achieve in life, what i believe is that the world holds together because of the love and relationships we have with each other we meet on our journey through life.

I give my 100% to anything i set my heart to because it is when you truly believe in something that you will actually set out to achieve it. And so continues my life in the software industry with many more challenges ahead which i gladly look forward to.

All i can say is that it has been one heck of a ride up until now, and what ever path God chose for me i shall walk since "I can do all things through Christ who strengthens me. Philippians 4:13"

Have a great day everyone... Take care and God bless

Monday, August 20, 2012

Lazy/Eager loading using hibernate by example

Today's post will focus on why and how we use the concepts known as LAZY and EAGER loading in an application and how to use Spring's hibernate template to load our LAZY entities in an EAGER fashion.

And of course as the title itself suggests, we will show this by an example. The scenario is as such;

You are a parent who has a kid with a lot of toys. But the current issue is whenever you call him (we assume you have a boy), he comes to you with all his toys as well. Now this is an issue since you do not want him carrying around his toys all the time.

So being the rationale parent, you go right ahead and define the toys of the child as LAZY. Now whenever you call him, he just comes to you without his toys.

But you are faced with another issue. When the time comes for a family trip, you want him to bring along his toys because the kid will be bored with the trip otherwise. But since you strictly enforced LAZY on the child's toy, you are unable to ask him to bring along the toys. This is where EAGER fetching comes into play. Let us first see our domain classes.




 
package com.fetchsample.example.domain;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Holds information about the child
 * 
 * @author dinuka.arseculeratne
 * 
 */
@Entity
@Table(name = "CHILD")
@NamedQuery(name = "findChildByName", query = "select DISTINCT(chd) from Child chd left join fetch chd.toyList where chd.childName=:chdName")
public class Child {

 public static interface Constants {
  public static final String FIND_CHILD_BY_NAME_QUERY = "findChildByName";

  public static final String CHILD_NAME_PARAM = "chdName";
 }

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 /**
  * The primary key of the CHILD table
  */
 private Long childId;

 @Column(name = "CHILD_NAME")
 /**
  * The name of the child
  */
 private String childName;

 @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
 /**
  * The toys the child has. We do not want the child to have the same toy more than
  * once, so we have used a set here.
  */
 private Set<Toy> toyList = new HashSet<Toy>();

 public Long getChildId() {
  return childId;
 }

 public void setChildId(Long childId) {
  this.childId = childId;
 }

 public String getChildName() {
  return childName;
 }

 public void setChildName(String childName) {
  this.childName = childName;
 }

 public Set<Toy> getToyList() {
  return toyList;
 }

 public void addToy(Toy toy) {
  toyList.add(toy);
 }

}

 
package com.fetchsample.example.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Hols data related to the toys a child possess
 * 
 * @author dinuka.arseculeratne
 * 
 */
@Entity
@Table(name = "TOYS")
public class Toy {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name = "TOY_ID")
 /**
  * The primary key of the TOYS table
  */
 private Long toyId;

 @Column(name = "TOY_NAME")
 /**
  * The name of the toy
  */
 private String toyName;

 public Long getToyId() {
  return toyId;
 }

 public void setToyId(Long toyId) {
  this.toyId = toyId;
 }

 public String getToyName() {
  return toyName;
 }

 public void setToyName(String toyName) {
  this.toyName = toyName;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((toyName == null) ? 0 : toyName.hashCode());
  return result;
 }

 @Override
 /**
  * Overriden because within the child class we use a Set to
  * hold all unique toys
  */
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Toy other = (Toy) obj;
  if (toyName == null) {
   if (other.toyName != null)
    return false;
  } else if (!toyName.equals(other.toyName))
   return false;
  return true;
 }

 @Override
 public String toString() {
  return "Toy [toyId=" + toyId + ", toyName=" + toyName + "]";
 }

}

So as you can see, we have two simple entities representing the child and toy. The child has a one-to-many relationship with the toys which means one child can have many toys (oh how i miss my childhood days). Afterwards we need to interact with the data, so let us go ahead and define out DAO(Data access object) interface and implementation.
 
package com.fetchsample.example.dao;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fetchsample.example.domain.Child;

/**
 * The basic contract for dealing with the {@link Child} entity
 * 
 * @author dinuka.arseculeratne
 * 
 */
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public interface ChildDAO {

 /**
  * This method will create a new instance of a child in the child table
  * 
  * @param child
  *            the entity to be persisted
  */
 public void persistChild(Child child);

 /**
  * Retrieves a child without his/her toys
  * 
  * @param childId
  *            the primary key of the child table
  * @return the child with the ID passed in if found
  */
 public Child getChildByIdWithoutToys(Long childId);

 /**
  * Retrieves the child with his/her toys
  * 
  * @param childId
  *            the primary key of the child table
  * @return the child with the ID passed in if found
  */
 public Child getChildByIdWithToys(Long childId);

 /**
  * Retrieves the child by the name and with his/her toys
  * 
  * @param childName
  *            the name of the child
  * @return the child entity that matches the name passed in
  */
 public Child getChildByNameWithToys(String childName);

}


 
package com.fetchsample.example.dao.hibernate;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;

/**
 * The hibernate implementation of our {@link ChildDAO} interface
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class ChildDAOHibernateImpl extends HibernateDaoSupport implements
  ChildDAO {

 /**
  * {@inheritDoc}
  */
 public void persistChild(Child child) {
  getHibernateTemplate().persist(child);
 }

 /**
  * {@inheritDoc}
  */
 public Child getChildByIdWithoutToys(Long childId) {
  return getHibernateTemplate().get(Child.class, childId);
 }

 /**
  * {@inheritDoc}
  */
 public Child getChildByIdWithToys(Long childId) {
  Child child = getChildByIdWithoutToys(childId);
  /**
   * Since by default the toys are not loaded, we call the hibernate
   * template's initialize method to populate the toys list of that
   * respective child.
   */
  getHibernateTemplate().initialize(child.getToyList());
  return child;
 }

 /**
  * {@inheritDoc}
  */
 public Child getChildByNameWithToys(String childName) {
  return (Child) getHibernateTemplate().findByNamedQueryAndNamedParam(
    Child.Constants.FIND_CHILD_BY_NAME_QUERY,
    Child.Constants.CHILD_NAME_PARAM, childName).get(0);

 }

}

A simple contract. I have four main methods. The first one of course just persists a child entity to the database.

The second method retrieves the Child by the primary key passed in, but does not fetch the toys.

The third method first fetches the Child and then retrieves the Child's toys using the Hibernate template's initialize() method. Note that when you call the initialize() method, hibernate will fetch you LAZY defined collection to the Child proxy you retrieved.

The final method also retrieves the Child's toys, but this time using a named query. If we go back to the Child entity's Named query, you can see that we have used "left join fetch". It is the keyword fetch that actually will initialize the toys collection as well when returning the Child entity that qualifies. Finally i have my main class to test our functionality;
 
package com.fetchsample.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;
import com.fetchsample.example.domain.Toy;

/**
 * A test class
 * 
 * @author dinuka.arseculeratne
 * 
 */
public class ChildTest {

 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext(
    "com/fetchsample/example/spring-context.xml");

  /**
   * First we initialize a child
   */
  Child child = new Child();

  /**
   * A cool ben 10 action figure
   */
  Toy ben10 = new Toy();
  ben10.setToyName("Ben 10 figure");

  /**
   * A even more cooler spider man action figure
   */
  Toy spiderMan = new Toy();
  spiderMan.setToyName("Spider man figure");

  child.setChildName("John");
  /**
   * Add the toys to the collection
   */
  child.addToy(ben10);
  child.addToy(spiderMan);

  ChildDAO childDAO = (ChildDAO) context.getBean("childDAO");

  childDAO.persistChild(child);

  Child childWithoutToys = childDAO.getChildByIdWithoutToys(1L);
  // The following line will throw a lazy initialization error since we have
  // defined fetch type as LAZY in the Child domain class.
  // System.out.println(childWithToys.getToyList().size());

  Child childWithToys = childDAO.getChildByIdWithToys(1L);
  System.out.println(childWithToys.getToyList().size());

  Child childByNameWithToys = childDAO.getChildByNameWithToys("John");

  System.out.println(childByNameWithToys.getToyList().size());

 }
}

Defining your base Entity as LAZY is a good practice since in many occasions, you might not want the collections within an entity, but just want to interact with the data in your base entity. But in the event of you needing the data of your collections, then you can use either of the methods mentioned before.

That is about it for today. For anyone who wants to try out the example, i have uploaded it here.

 Thank you for reading, and hope you have a great day. Cheers!!

Friday, April 20, 2012

Setting up JNDI with Jetty (Embedded)

I was running embedded Jetty on my development work-space saving some time on vicious cycle of compiling and deployment. I have not worked with Jetty much and the ease of use made me hook on to it. I was in need to setup JNDI in order to retrieve a connection pool for my database related activities. Though there were comprehensive documentation in some places, most were scattered. So this post is intended to be your one stop place for the requirement of setting up JNDI with Jetty. If it does not, please do leave a comment and i will be glad to help you out.

So starting off, first let us see how to setup Jetty to run as an embedded server. The folder structure of my eclipse project is as follows;



The etc folder will consist of all the configuration files required by jetty. You can download jetty from here. For this example i have used jetty-6.1.26.

Include the following jars from the given folder locations;


lib
jetty-x.x.xx.jar, jetty-util-x.x.xx.jar,servlet-api-x.x.jar
lib/plus
jetty-plus-x.x.xx.jar
lib/naming
jetty-naming-x.x.xx.jar


For my example, i have set up mysql and therefore mysql-connector jar is also included in my library path.

Copy all the files residing in your jetty installation's etc directory to the etc directory of your eclipse project.

In order to enable JNDI, we first need to include jetty-plus. There are many ways you can do this such as providing it as a run-time argument, including it within your own jetty-env.xml residing in your WEB-INF or copying and pasting the required xml snippets from the jetty-plus.xml to your jetty.xml. I have chosen the latter. Hence, i have included the following snippet within my jetty.xml;


   <Array id="plusConfig" type="java.lang.String">
    <Item>org.mortbay.jetty.webapp.WebInfConfiguration</Item>
    <Item>org.mortbay.jetty.plus.webapp.EnvConfiguration</Item>
    <Item>org.mortbay.jetty.plus.webapp.Configuration</Item>
    <Item>org.mortbay.jetty.webapp.JettyWebXmlConfiguration</Item>
    <Item>org.mortbay.jetty.webapp.TagLibConfiguration</Item>
  </Array>

<call name="addLifeCycle">
      <arg>
        <new class="org.mortbay.jetty.deployer.WebAppDeployer">
          <set name="contexts"><ref id="Contexts"></ref></set>
          <set name="webAppDir"><systemproperty default="." name="jetty.home">/webapps</systemproperty></set>
          <set name="parentLoaderPriority">false</set>
          <set name="extract">true</set>
          <set name="allowDuplicates">false</set>
          <set name="defaultsDescriptor"><systemproperty default="." name="jetty.home">/etc/webdefault.xml</systemproperty></set>
          <set name="configurationClasses"><ref id="plusConfig"></ref></set>
        </new>
      </arg>
</call>
Next up, you need to add the XML fragment related to your data-source into your jetty.xml. I have added the snippet required for mysql. For any other database, please check this link.
 
  <New id="myds" class="org.mortbay.jetty.plus.naming.Resource">

     <Arg>jdbc/MySQLDS</Arg>
     <Arg>
        <New class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">
           <Set name="Url">jdbc:mysql://localhost:3306/test</Set>
           <Set name="User">root</Set>
           <Set name="Password">password</Set>
        </New>
     </Arg>
</New>
Now that we have setup everything, all you need to do is run jetty in your embedded environment. Following code shows you how to run Jetty in the embedded mode as part of your main class;
 
import java.io.File;

import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.DefaultHandler;
import org.mortbay.jetty.handler.HandlerList;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.xml.XmlConfiguration;




public class JettyTest {

 public static void main(String[] args) throws Exception {
  Server jetty = new Server();
  String[] configFiles = {"etc/jetty.xml"};
  for(String configFile : configFiles) {
  XmlConfiguration configuration = new XmlConfiguration(new File(configFile).toURI().toURL());
  configuration.configure(jetty);
  }
  
  WebAppContext appContext = new WebAppContext();
  appContext.setContextPath("/myapp");
  File rd = new File("path_to_your_war_file");
  appContext.setWar(rd.getAbsolutePath());
  HandlerList handlers = new HandlerList();
  handlers.setHandlers(new Handler[]{ appContext, new DefaultHandler()});
  jetty.setHandler(handlers);
  jetty.start();
 }
}

Thats about it. Now you can look up your data-source which is exposed from Jetty. For ease, i have configured it with Spring's JNDIObjectFactoryBean. One important aspect to note is the jndi provider URL and the initial context factory entries required for Jetty.
 
  <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
        <property name="environment">
            <props>
                <prop key="java.naming.factory.initial">org.mortbay.naming.InitialContextFactory</prop>
                <prop key="java.naming.provider.url">org.mortbay.naming</prop>
            </props>
        </property>
    </bean>
    
    <bean id="jndiDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
   
        <property name="jndiTemplate">
          <ref bean="jndiTemplate"/>
        </property>
        <property name="jndiName">
              <value>jdbc/MySQLDS</value>
        </property>
      </bean>
With that you have all that you need to configure JNDI and access it through Spring's JNDI template. One other thing i was interested in was remote debugging with jetty server. After some searching i found that you need to include the following in your runtime configuration as VM arguments;
-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000
This will enable you to remote debug your application on port 8000. If there are any queries please do leave a comment and i will be more than happy to help anyone. And ofcourse if you do see any error, leave a reply too which again is much appreciated :).
Good day to you all and thank you for taking the time to read!!

Wednesday, January 11, 2012

Understanding Java References

Playing around with Java References:

I could not pay attention to the blog in the recent times and first and foremost I must apologize for not staying in touch with you all in the world of technology. I recently stumbled upon the java.lang.ref package which was available since Java 1.2 but ironically i got to know about it just a few days back. Going through a few articles explaining about the various reference types and the java doc as well, I was very much intrigued and was anxious to get my hands dirty with some reference related code.

Im not going to talk about each reference class available within the java.lang.ref package as it is already very well explained here. Let us take a look at the following code snippet which I wrote to understand the basic operation of a WeakReference.

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class ReferencesTest {

 private WeakReference<Map<Integer, String>> myMap;

 public static void main(String[] args) {
  new ReferencesTest().doFunction();
 }

 private void doFunction() {

  Map<Integer, String> map = new HashMap<Integer, String>();
  myMap = new WeakReference<Map<Integer, String>>(map);

  map = null;
  int i = 0;
  while (true) {
   if (myMap != null && myMap.get() != null) {
    myMap.get().put(i++, "test" + i);

    System.out.println("im still working!!!!");
   } else {

    System.out
      .println("*******im free*******");

   }

  }
 }
}
First I have defined a weak reference instance variable to which I assign an instance of a HashMap initialized within the doFunction() method. Then data is input to the map via the weak reference instance and not directly through the concrete instance of the hashmap we created. We check for the map being null due to the fact of the way WeakReferences work.

During the execution of the program, a weak reference will be the first to be garbage collected if there are no soft or strong references binding to it. So if memory is considerably low, or when and if the garbage collector deems appropriate, the weak reference is garbage collected and this is why I have included the else statement within my code to show the occurrence of that situation. Run this by setting minimum –Xms and –Xmx to understand how it works since otherwise you will have to wait a longer period to get an out of memory exception. And then change the WeakReference implementation to a SoftReference implementation and see that the program actually crashes after a few iterations. This is due to the fact that SoftReferences only gurantee to clean up memory just before a OutOfMemory error occurs. But with the WeakReference, the program continues to function without halting because it is almost always eligible for garbage collection and we can reinitialize the cache and continue to repopulate our cache.

The good thing about weak reference is that in my opinion it is one of the best ways to implement an in-memory cache which we usually implement ourselves when we need to keep data that do not consistently change but frequently accessed in memory and when the cost of going for a fully-fledged caching implementation like the JBoss cache or EHCache is too much. Quite often I have implemented caching solutions and have also seen production code similar to the following code snippet;

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

public class CacheTest {

 private Map<String, Object> myAwesomeCache = new HashMap<String, Object>(100);
 
 public Object getData(String id){
  
  Object objToReturn = null;
  
  if(myAwesomeCache.containsKey(id)){
   objToReturn = myAwesomeCache.get(id);
  }else{
   // retrieve from the database and populate the in memory cache map
  }
  
  return objToReturn;
 }
}


This is just a very basic level implementation to put out the idea across that we sometimes do use Maps to construct in-memory caching implementations. The fact that we have to note is that though there is nothing intrinsically wrong with this implementation, in an instance where your application is running low on memory, it would be a ideal if the garbage collector could remove this from memory to free up some for the other processes that need it. But since this map is a strong reference, there is no way the garbage collector can mark this reference as eligible for collection. A better solution would be to change the caching implementation from HashMap to a WeakHashMap.

The Javadoc specifies the following about the WeakHashMap;

         "A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will   automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations."

So in retrospect, I believe whenever you are in need of an in-memory caching implementation and memory is of utmost importance to you, using a WeakHashMap would be beneficial.

That concludes my findings on the Reference package and I invite you all to share your experience in this regard which is highly appreciated.

Cheers