Pages

Sending Email with Java and Akka actors

Akka is a concurrent framework written by Scala.

Here I demonstrate sample application to send emails with Akka and implemented in Java.

Reasons I decided to use Akka framework other than concurrency.
  • Built-in configurable supervisor strategy to monitor child workers and decide what policy applies when there is an exception.
  • Can reschedule delivery when application throwing some specific exception.
  • Use of actor routers and allow them to use actor connection pool.

Here is how to create supervision strategy.

 class EmailServiceActor extends UntypedActor {  
   private static SupervisorStrategy strategy =  
       new OneForOneStrategy(10, Duration.create("1 minute"),  
           new Function<Throwable, Directive>() {  
             @Override  
             public Directive apply(Throwable t) {  
               if (t instanceof MessagingException) {  
                 return resume();  
               } else if (t instanceof Exception) {  
                 return stop();  
               } else {  
                 return escalate();  
               }  
             }  
           });  
   @Override  
   public void onReceive(Object message) {  
     getContext().actorOf(new Props(EmailServiceWorker.class)).tell(message, self());  
   }  
   @Override  
   public SupervisorStrategy supervisorStrategy() {  
     return strategy;  
   }  
 }  

Here is how child worker create


 class EmailServiceWorker extends UntypedActor {  
   @Override  
   public void onReceive(Object message) {  
     try {  
       EmailService emailService = new EmailService();  
       emailService.sendEmail();  
     } catch (IOException e) {  
       e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.  
     } catch (MessagingException e) {  
       e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.  
     }  
   }  
   @Override  
   public void preStart() {  
 //    getContext().system().scheduler().scheduleOnce(Duration.create(5, TimeUnit.SECONDS), self(), "emailWorker", getContext().system().dispatcher(), null);  
   }  
   @Override  
   public void postStop() {  
   }  
 }  


Sample application -  https://github.com/rajithd/email-service-akka

Install CouchDB 1.3 in Ubuntu 12.04 64bit

Here are the steps to install couchDB 1.3 in Ubunutu 12.04 64bit
Step 1
 execute following command set to install required dependencies


 sudo apt-get install g++  
 sudo apt-get install erlang-base erlang-dev erlang-eunit erlang-nox  
 sudo apt-get install libmozjs185-dev libicu-dev libcurl4-gnutls-dev libtool  

Step 2
Then go to couchDB site and download source.

Step 3
Extract it and execute following commands.

 ./configure  
 make  
 sudo make install  

Step 4
To start the couchDB service run the following command.

 sudo couchdb  

Producer Consumer Problem with Blocking Queue

Producer Consumer problem is a popular problem domain in SE industry. Its hard find anyone who doesn't have heard it.
So in this post I will solve this producer consumer problem by using Blocking Queue in java.

Before that I will give a quick introduction of Blocking Queue.

Blocking Queue is an interface locate in java concurrent package.It mainly support operations that wait for the queue to become non empty when retrieving and removing element and wait for space become available when adding an element. All the blocking queue implementation are thread-safe and methods are atomic.

In this demo I will use ArrayBlockingQueue as the implementation of BlockQueue.

So first we create domain model for this demo.
Message.java

 package rd.domain;  
 public class Message {  
   private String description;  
   public String getDescription() {  
     return description;  
   }  
   public void setDescription(String description) {  
     this.description = description;  
   }  
 }  

then we create Producer.java
create 100 message and finish message and add in to the queue.

 package rd.concurent;  
 import rd.domain.Message;  
 import java.util.concurrent.BlockingQueue;  
 public class Producer implements Runnable {  
   private BlockingQueue<Message> queue;  
   public Producer(BlockingQueue<Message> queue) {  
     this.queue = queue;  
   }  
   @Override  
   public void run() {  
     // create messages and adding to queue  
     for (int i = 1; i <= 100; i++) {  
       Message message = new Message();  
       message.setDescription(" Message " + i);  
       try {  
         Thread.sleep(i);  
         queue.put(message);  
         System.out.println("Produced " + message.getDescription());  
       } catch (InterruptedException e) {  
         e.printStackTrace();  
       }  
     }  
     // adding exit message  
     Message message = new Message();  
     message.setDescription("finish");  
     try {  
       queue.put(message);  
     } catch (InterruptedException e) {  
       e.printStackTrace();  
     }  
   }  
 }  

Consumer.java


 package rd.concurent;  
 import rd.domain.Message;  
 import java.util.concurrent.BlockingQueue;  
 public class Consumer implements Runnable {  
   private BlockingQueue<Message> queue;  
   public Consumer(BlockingQueue<Message> queue) {  
     this.queue = queue;  
   }  
   @Override  
   public void run() {  
     Message message = null;  
     try {  
       while (!(message = queue.take()).getDescription().endsWith("finish")){  
         Thread.sleep(10);  
         System.out.println("Consumed " + message.getDescription());  
       }  
     } catch (InterruptedException e) {  
       e.printStackTrace();  
     }  
   }  
 }  

So the basic implementation are done. Now its time to test it. Here I create Main.java and create producer consumer thread and start those threads.

Main.java


 package rd;  
 import rd.concurent.Consumer;  
 import rd.concurent.Producer;  
 import rd.domain.Message;  
 import java.util.concurrent.ArrayBlockingQueue;  
 import java.util.concurrent.BlockingQueue;  
 public class Main {  
   public static void main(String[] args) {  
     BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue<>(10);  
     Producer producer = new Producer(blockingQueue);  
     Consumer consumer = new Consumer(blockingQueue);  
     new Thread(consumer).start();  
     new Thread(producer).start();  
     System.out.println("Started.................");  
   }  
 }  

So that's it. We just solved the producer consumer problem.

Resolve “java.lang.OutOfMemoryError: PermGen space” error in Maven

If your project have more than 10 modules and your building tool is maven you would face this exception that comes into your console.

 java.lang.OutOfMemoryError: PermGen space  
     at java.lang.ClassLoader.defineClass1(Native Method)  
     at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)  
     at java.lang.ClassLoader.defineClass(ClassLoader.java:616)  

to avoid this just execute the following command in console.

 set MAVEN_OPTS=-XX:MaxPermSize=512m  

But sometime you have to provide the double quotes as well.

 set MAVEN_OPTS="-XX:MaxPermSize=512m"  

Access Private methods and Fields with Java Reflection

Java Reflection, guess you heard it.But I will give a little bit of introduction and show some code sample to get familiar with this.
OK so the first thing first.
What is Java Reflection ?
Java Reflection can be used to dynamically find java classes , locating and execute methods, access fields at run time.

You can find More on : http://docs.oracle.com/javase/tutorial/reflect/index.html

Here is the sample project that I did.

First I create a class called dynamic test and add one private field and four methods including one private methods. Here is the code and its straight forward.

 package rd.test;  
 public class DynamicTest {  
   private int count;  
   public void printStar() {  
     System.out.println("*");  
   }  
   public void printStarWithInt(int i) {  
     System.out.println("* Integer : " + i);  
   }  
   public void printStarWithString(String param) {  
     System.out.println("* String : " + param);  
   }  
   public void printStarWithStrings(String param1, String param2) {  
     System.out.println("* String : " + param1 + " , and " + param2);  
   }  
   private void printStarInPrivate() {  
     System.out.println("* Private : *");  
   }  
 }  

and here is the class with main method.


 package rd;  
 import rd.test.DynamicTest;  
 import java.lang.reflect.Field;  
 import java.lang.reflect.InvocationTargetException;  
 import java.lang.reflect.Method;  
 public class Main {  
   public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException,  
       InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {  
     Class cls = Class.forName("rd.test.DynamicTest");  
     Object obj = cls.newInstance();  
     /**  
      * calling printstart method without passing any parameters  
      * */  
     Method method = cls.getDeclaredMethod("printStar", null);  
     method.invoke(obj, null);  
     /**  
      * calling printStarWithInt method with int parameter  
      */  
     Class[] intParam = new Class[1];  
     intParam[0] = Integer.TYPE;  
     method = cls.getDeclaredMethod("printStarWithInt", intParam);  
     method.invoke(obj, 100);  
     /**  
      * calling printStarWithStrings methos with two string parameters  
      */  
     Class[] stringParams = new Class[2];  
     stringParams[0]=String.class;  
     stringParams[1]=String.class;  
     method = cls.getDeclaredMethod("printStarWithStrings", stringParams);  
     method.invoke(obj, "hi","rajith");  
     /**  
      * calling private method in DynamicTest class  
      */  
     method = cls.getDeclaredMethod("printStarInPrivate", null);  
     method.setAccessible(true);  
     method.invoke(obj, null);  
     /**  
      * setting and getting private fileds  
      */  
     DynamicTest dynamicTest = new DynamicTest();  
     Field field = cls.getDeclaredField("count");  
     field.setAccessible(true);  
     field.setInt(dynamicTest,10);  
     System.out.println(field.get(dynamicTest));  
   }  
 }  

I explained most of the things with the comments. How to access private fields and methods, how to pass different type of parameters and all.