SyntaxHighlighter

Tuesday, July 5, 2011

Java 7 New Features

Following are few new features of Java 7

1. Introduction of WatchService? (NIO)

A watch service that watches registered objects for changes and events. For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.

2. Strings in Java Switch construct
Will be able to String case based switch constructt; prior to java 7 switch was only allowed with int & enums

3. Introduction of autoclosable interface and try with resource construct
Developers will get rid of closing resources in finally block. JDBC 4.1 has accomodated these constructs in their classes.
4. Underscores in Numbers
Increasing readability of numbers.
int phoneNumber = 555_555_1212;
long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumbers = 999_99_9999L;
float monetaryAmount = 12_345_132.12;
long hexBytes = 0xFF_EC_DE_5E;

5. Introduction of Closures
Much awaited & requested closures are part of JDK7 on experimental basis ,RI for it will be included in JDK8 TCK as per JSR


6 Addition of forkJoin for parallel processing
Combined JSR 166 into JDK

Monday, July 4, 2011

Spring - MongoDB (Document Oriented Database)

We often hear following terms viz high scalability, elasticity , high availability..
In addition to this, we do face performance issues with humongous data , which brings our critical applications to deadly halt.

I have experienced such performance problems numerous times in my professional carrier (almost 6 years til now), we usually solved these problems with trade offs like minimizing data fetched / even gone ahead and moved on to more cores and disks etc or tuning and other stuff.

Having such a experience , I was always looking to try out thing called NOSQL databases, recently I got chance & time

My first reaction to Mongo was ..."Its Kool !!".

I tried MongoDB along with spring , (spring-data mongodb), as always spring provides nice abstraction and spring style templates to interact with mongo.

 Setting up MongoDB is very simple,
1. Download zip from http://www.mongodb.org/downloads appropriate for your platform.For me its mongodb-win32-i386-1.8.1.zip
2. Unzip the zip the downloaded zip to a directory, it will have a bin directory with mongo executables.
3. To get mongo working create "C:\data\db\"  ,as mongo uses this location as default to store file system.
4. You are almost done, now go to bin directory and run mongod.exe , this will start up database server.
5. "help' command will help you after that, to explore more functions like creating database, switching, adding users, adding updating/ removing collections.

Now, will move to spring -mongo part,

Spring comes with MongoTemplate, 
sample configurations , that I tried are as follows



The class MongoRepository is a implementation of below interface with mongotemplate instance injected in it



Constructor of MongoRepository initializes a mongoTemplate instance as follows



 It works very smoothly..

 @Override
    public void saveEntity(String collectionName, Entity object,com.dhananjay.ithinker.persister.Repository.Mode mode) {
        log.info("Saving record for in Collection Name "+collectionName);
        switch(mode){
            case INSERT:
                this.mongoTemplate.insert(collectionName,object);
                break;
            case UPDATE:
            { 
                Map objectMap;
                try {
                    objectMap = org.apache.commons.beanutils.BeanUtils.describe(object);
                    Update update = new Update();
                    if(objectMap != null && !objectMap.isEmpty()){
                      
                        for(Map.Entry entry : objectMap.entrySet()){
                            if(entry.getValue() != null)
                                //update.addToSet(entry.getKey(), entry.getValue());
                                update = update.set(entry.getKey(), entry.getValue());
                            this.mongoTemplate.updateFirst(collectionName,new Query(where("_id").is(object.getId())), update);
                        }
                    }
                  
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Error while update ",e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException("Error while update ",e);
                } catch (NoSuchMethodException e) {
                    throw new RuntimeException("Error while update ",e);
                }
                break;
            }
            case DELETE:
                this.mongoTemplate.remove(collectionName,new Query(where("_id").is(object.getId())));
                break;
            default :
                throw new UnsupportedOperationException("This mode for DB operation is not yet supported "+mode);
      
        }
      
        log.info("Saving record for in Collection Name is completed"+collectionName);
    }


@Override
    public T getEntityByColumn(String column, String value,String collection, Class clazz) {
        return this.mongoTemplate.findOne(collection, new Query(where(column).is(value)),clazz);
    }

    @Override
    public T getEntityById(String collectionName, long id,Class clazz) {
        log.info("Fetching single record for id "+id +" Collection Name "+collectionName);
        return this.mongoTemplate.findOne(collectionName, new Query(where("_id").is(id)),clazz);
    }


MongoRepository

 HUMONGOUS  :)
Thanks,
Dhananjay

Thursday, December 16, 2010

Spring Remoting Over JMS

JMS is one of the robust and widely used application integration style.
In this era of building loosely coupled service component based enterprise application; we often need to communicate with other application..exchange data...invoke operations.

Such inter JVM communication is made simpler and more robust by Spring's remoting support over JMS.
Its as simple as invoking a local object method.

Spring does it very transparently, with the help of JmsInvokerServiceExporter ,SimpleMessageListenerContainer and JmsInvokerProxyFactoryBean.
You just need to aware of these 3 classes and off course JMS connectionFactory and queue /topic definition.
First will define JMS related beans such as connectionFactory and Queue as follows:
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://localhost:61616"/>
bean>

<bean id="salaryQueue" class="org.apache.activemq.command.ActiveMQQueue">
     <constructor-arg value="salaryCalculatorQueue"/>
 bean>


Now how to expose a pojo Calculator.java service for remoting over JMS using JMSInvokerServiceExporter
<bean id="calculatorService"    class="com.patkard.spring.remoting.service.impl.SalaryCalculator">
bean>
     
<bean id="remoteCalculatorService" class="org.springframework.jms.remoting.JmsInvokerServiceExporter">
        <property name="service" >
              <bean   class="com.patkard.spring.remoting.service.impl.SalaryCalculator">bean>
        property>
        <property name="serviceInterface"   value="com.patkard.spring.remoting.service.Calculator" />
bean>
Above JMSInvokerServiceExporter exposes Calculator service for remoting over JMS;  here you can also specific method which you wish to expose for remoting.

Define a listener for the queue and provide service bean reference for listener as follows


<bean class="org.springframework.jms.listener.SimpleMessageListenerContainer">
       <property name="connectionFactory" ref="connectionFactory"/>
       <property name="destination" ref="salaryQueue"/>
       <property name="concurrentConsumers" value="3"/>
       <property name="messageListener" ref="remoteCalculatorService"/>
   bean> 
On the client Side; there will be a JmsInvokerProxyFactoryBean definition which will invoke remote method / basically acts as event sender
 
<bean id="remoteCalculatorService" class="org.springframework.jms.remoting.JmsInvokerProxyFactoryBean">
     <property name="serviceInterface" value="com.patkard.spring.remoting.service.Calculator" />
     <property name="connectionFactory" ref="connectionFactory">property>
     <property name="queue" ref="salaryQueue">property>
 bean>          
 The connection Factory and Queue bean definitions are shared by both the client and server configurations


Before running client / server main programs ..start up Active MQ server.

write a simple main program to start up server like below..just load server side bean definitions


ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/remoting/jms/remoting-context-server.xml");
System.out.println("Started Server application...");

write simple client program..look up Calculator bean and invoke a method on bean as if your invoking a local object method.

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/remoting/jms/remoting-context-client.xml");
Calculator calculator = (Calculator)applicationContext.getBean("remoteCalculatorService");
Employee employee = new Employee(12,”Dhananjay”);
employee.setGrade(1);
long sal = calculator.calculateSalary(employee);
System.out.println("Salary Returned "+sal);    
Simple isn't it?


Cheers,
Dhananjay

















Friday, December 10, 2010

Spring Quartz Priority Job Queue

Following post describes how to build a Priority Quartz Job queue.

Basic and most important factor in this is to define (Spring's SchedulerFactory bean )Quartz scheduler with single worker thread.

This can be defined in spring configuration as follows
 <bean id="springScheduler"
                class="org.springframework.scheduling.quartz.SchedulerFactoryBean" destroy-method="destroy">
                <property name="applicationContextSchedulerContextKey" value="applicationContext">property>
                <property name="quartzProperties">
                        <props>
                                <prop key="org.quartz.threadPool.threadCount"> 1 prop>
                        props>
                property>bean> 

As worker thread count is 1; this scheduler can run a one job at a time.

Now will write a Queue Job; which will be taking care of priority while executing individual jobs.

QueueJobBean.java is extension to spring's QuartzJobBean and internally maintains a TreeMap containing job names (spring bean names) with priorities.

<bean name="jobQueue" class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass" value="scheduler.QueueJobBean" />
        <property name="jobDataAsMap" ref="prioMap">property>
bean>

We can build a Priority Job map within spring bean configuration as below
<bean id="noOperation" class="scheduler.jobs.NoOpJob" >
    bean>
   
    <util:map id="prioMap" map-class="java.util.TreeMap">
        <entry key="1" value="noOperation"/>
        <entry key="2" value="noOperation"/>
        <entry key="3" value="noOperation"/>
    util:map>

Cheers,
Dhananjay