Sunday, 22 November 2015


NFS mount is used to share a directory between several servers, It saves the disk Space and is Useful for a Infrastructure where a application shares a common directory and is hosted in multiple instances.

Lets think we have a Rails application where we upload a csv file and save it a directory in server with file name to DB .

On the other hand a Rake Task/ Cron Job runs every two minutes that polls DB for file name and proccess the CSV file to get the desired response.

It works fine when we have a single instance hosted in server, think if we have two instances of Rails in different Server and is managed by a Load balancer to server request.

When a File Upload Request comes to ELB , it directs to instance1 with file1 and the second request to instance 2 with file2, The cron job in instance 2 picks the file name file1 from DB and doesnot found any matching file and Marks FILE NOT FOUND IN DB , where as file is present in instance1.

To avoid this type of issues we can use S3 which we can get py paying few amount, the Opensource way is Using NFS Mount, Lets Check how to Configure NFS.

Lets Say we have two instances with IP:

Lets Configure
NFS-Master :
NFS - Client :

Execute the following Commands:
sudo su 
yum install nfs-utils nfs-utils-lib
Startup Scripts :

chkconfig nfs on 
service rpcbind start 
service nfs start

EXPORT the Shared Directory :

Suppose we want the directory /home/rails/upload_dir , to be shared between the instances.

Open vi /etc/exports
Add the following lines at EOF
then execute :
exportfs -a
service nfs restart
SSH to server

Execute following commands:

yum install nfs-utils nfs-utils-lib
#Assuming the upload_dir path is same as instance1
mkdir -p /home/rails/upload_dir
mount /home/rails/upload_dir

You Can verify it by typing:
df –h
Filesystem            Size  Used Avail Use% Mounted on /dev/sda               20G  783M   18G   5% / 20G  785M   18G   5% /home/rails/upload_dir
nano /etc/fstab
Add the following line:  /home/rails/upload_dir nfs      defaults,_nfs_shared 0 0
Try creating a file in instace1 of shared dir and check it should be populated in instance2 of shared dir(/home/rails/upload_dir)

Keep in Mind Once the NFS Mount is unmounted all the data will be lost from the mounted instance , but data will be safe in Master instance.

This post is created by Santosh Mohanty . You can contact him for any questions at or message him on his linkedIn profile .

Tuesday, 17 November 2015

Search And Replace String in ByteBuffer

This is a simple java program which will search and replace a particular String in ByteBuffer
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class ByteBufferTest {
  public static void main(String[] args)
    String fullText = "javarootsbestwebsiteoftheyear";
    String search = "website";
    String replace = "blog";
    ByteBuffer input = ByteBuffer.wrap(fullText.getBytes());
    byte[] toSearch = search.getBytes();
    int index = getIndex(input, toSearch);
    byte[] first = new byte[index];
    byte[] second = replace.getBytes();
    ByteBuffer finalOne = ByteBuffer.allocate(first.length+second.length+input.remaining());
    CharBuffer result = Charset.forName("UTF-8").decode(finalOne);
    String s = result.toString();
  public static int getIndex(ByteBuffer input , byte[] toSearch)
    int index = -1 ;
    while(input.hasRemaining() && index==-1)
      boolean found = true ;
      for(byte b : toSearch)
          found = false ;
          break ; 
        index= input.position()-toSearch.length;
    return index ;


Post Comments And Suggestions !!!

Monday, 9 November 2015

Beginners Guide to Jenkins

In this blog we will be learning how to use Continuous Integration tools to deploy Projects, Here I will be using Jenkins as CI and Maven as build tool to deploy Spring MVN Based Applications.
You can Install Jenkins through yum/apt-get for your Linux/Redhat Distributions, but I prefer to install jenkins as a home user so that it can access my tools like java,maven,capistrano,ruby,pscp and many different tools.

My Home directory here is /home/rails

Jenkins will be installed under /home/rails/.jenkins

To do this I will download the Jenkins.war file from jenkins repo

STEP 2 :
Execute the war file using this command

java -jar jenkins.war --httpPort=8080
You will view the following lines
Nov 05, 2015 1:14:43 AM hudson.WebAppMain$3 run
INFO: Jenkins is fully up and running

Access Jenkins through localhost:8080
You should View a Wonderful Jenkins Dashboard.
STEP 3 :

Create a User who can create jobs and build those, Let me make it easier for you:
•Click on Manage Jenkins => Configure Global Security
•Enable Security => Jenkins Own user Database.
•Under Authorization part, select Matrix based Security, For Anonymous User Under View select only Read Permission
•Now Click on Add and create a user named Admin and Grant All Access
•Click Save and Apply
•You will be redirected to Set up page enter your password and click Save.

Step 4:

Manage Plugins:

By Default Jenkins comes in with prebuilt plugins like svn, maven,scp for installing extra plugins you can go to availables tab and install.

Step 5:

Accessing Repository to download source code and build
•Here I will be using SVN & SSH
•As I am in my home directory I will be using my ~/.ssh/id_rsa Keys for Authentication
•Click on Add Credentials => Global Credential and enter your credentials
•Repo url: svn+ssh://
•SSH Authentication
Username : svn
Passphrase: ****** (Null if no Passphrase)
Private Key : Upload your id_rsa Key

Step 6:

Click on Create Job:
•Type Project Name
•Enter SVN Repo details
•Build => Invoke Top Level Maven Target
•Use Maven Version as Default
•Goal : clean -Dmaven.test.skip=true package -P prod
•Apply and Save.
Now Its Done.
If you need to send the build to some other location Enter your script in command shell this would do the Work.
Step 7:

Click on Build Now, The Build Should Work for you.

Now it should show you a success message.

Jenkins + Capistrano Integration Coming Soon.

This post is created by Santosh Mohanty . You can contact him for any questions at or message him on his linkedIn profile .

Wednesday, 2 September 2015

Why You Should Move to Rails 5

Every one of us is waiting for a new and clean release of Rails 5 , which not only accepts the SPA(Single Page Application) Implementation easily but also has enhanced the performance and structure of thr most popular Rails frame work.

The release of Rails 5 is supposed to be fall on summer/fall of 2015.

Lets discuss the rich changes/implementation of Rails 5.


SPA is on rise, while developing a Single page application we rails developers faced a lot of issues, the routing was lacked and there were several security vulnerabilities that we had to handle.

In Rails 5, the rails-api Gem will be merged into core allowing the use of Rails as Simple JSON API. Which ease building API using Javascript Library.


In Rails 5 all the current rake commands will be accessible via the rails command.
When you want to run a migration, you will type rake db:migrate in Rails 4. In Rails 5 this will become railsdb:migrate.
The reason for this change is that currently it's not very logical which command has to go through rake and which command should go through rails. When you're working with rails for a longer time it becomes second nature, but only because you remember it.
For a newcomer, this is a big problem and makes learning rails confusing.
See this issue on GitHub for more details .


You can now restart all of your apps with the command rake restart.
See this Pull Request for more details .


In Rails 5, the test helpers assigns() and assert_template() will be deprecated. Its because testing instance variable and what template is being called smells bad. These are internals of controller and controller tests should not care about what vars I set.
Controllers test are concerned about HTTP,Cookies, Renders, Redirects and so on.
More Details can be found here .


Rails will only support Ruby 2.2.1 and up. Since it wants to be able to leverage all the speed improvements in the newer ruby versions. They skipped version 2.2.0 since it has a segfault bug source.


For the folks who don’t like to meddle around with JS, Turbolinks offers an instantaneous performance boost, and allows you to retain most of your page and selectively update certain regions through partials. This is very similar to how SPA’s work, and you can choose to do all this from the server.


Many projects these days use WebSockets to push live updates to the client. While most client browsers(IE > 9, Chrome, Firefox, Safari) have started to support this, we still need a robust client on the server to manage the subscribers and send an update signal appropriately. This feature is available out of the box in some of the newer frameworks, like Phoenix for Erlang. However, the Rails community had to resort to third party implementations, like Pushr, to get this working.

Rails traditionally offers all the tools that one needs to build a great app out of the box. That’s one reason why it is so popular, especially among the startup community. The lack of WebSocket support was a reason for major discontent among the community. It looks like the Rails core team took note of this and came up with Action Cable.

As a Team of Ruby , Rails, Java,JS and CSS Developer we are Commited towards the trending technologies and simplifying developers and Clients Projects .

For any Information regarding Upgrading your Rails Application or building your ideas we welcome you to Our Community.

This post is created by Santosh Mohanty . You can contact him for any questions at or message him on his linkedIn profile .

How To Create Rest WebServices With GUICE And Jersey

This is a simple example of how to use Google Guice , with Jersey to create JAX-RS web services , which can be deployed to any servlet container like Tomcat , Jboss , GlassFish etc .

We will be creating a simple Transaction Service , which will Create , update , and query Transactions . For this example , we are not using any database but a simple hashmap to store it .

So , first of all lets have a look at our maven pom.xml file . I have added dependency for Guice(jersey-guice) which is a guice extension of jersey.

<project xmlns="" xmlns:xsi=""
 <name>Code Challenge</name>
 <description>Code Challenge Sample Prject</description>






Now we have DAO like this .
package com.javaroots.dao;

import java.util.List;

import com.javaroots.model.Transaction;

public interface TransferDAO {
 public void create(Transaction tr);
 public Transaction get(Long id) ;
package com.javaroots.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.javaroots.dao.TransferDAO;
import com.javaroots.model.Transaction;
public class TransferDAOMemoryImpl implements TransferDAO{

 private ReadWriteLock lock ;
 private Lock readLock ;
 private Lock writeLock ;
 private Map store ;
 public TransferDAOMemoryImpl()
  lock = new ReentrantReadWriteLock();
  readLock = lock.readLock();
  writeLock = lock.writeLock();
  store = new HashMap();
 public void create(Transaction t){
  if(t.getParent_id() !=null)
   Transaction parent = get(t.getParent_id());
   if(parent == null)
    throw new RuntimeException(" Invalid parent id . id not exist in system");
 public Transaction get(Long id) {
   return store.get(id);

Model Class :
package com.javaroots.model;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

public class Transaction {
 private Long id ;
 private Long parent_id ;
 private String type ;
 private Double amount ;
 public Transaction(){};
 public Transaction(Transaction t)
 { = ;
  this.parent_id = t.parent_id;
  this.type = t.type ;
  this.amount = t.amount ;
 public Long getId() {
  return id;
 public void setId(Long id) { = id;
 public Long getParent_id() {
  return parent_id;

 public void setParent_id(Long parent_id) {
  this.parent_id = parent_id;

 public String getType() {
  return type;
 public void setType(String type) {
  this.type = type;
 public Double getAmount() {
  return amount;
 public void setAmount(Double amount) {
  this.amount = amount;
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((id == null) ? 0 : id.hashCode());
  return result;
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Transaction other = (Transaction) obj;
  if (id == null) {
   if ( != null)
    return false;
  } else if (!id.equals(
   return false;
  return true;

Now following is our Rest Service class :

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.javaroots.dao.TransferDAO;
import com.javaroots.model.Transaction;

public class TransactionService {
 private TransferDAO transferDAO ;

 public TransactionService(TransferDAO transferDAO)
  this.transferDAO =  transferDAO ;
 public Response createTransaction(@PathParam("transaction_id")Long transactionId , Transaction entity) {
  Map map = new HashMap();
  return Response.status(Status.OK).entity(map).build();
 public Response getByType(@PathParam("transaction_id")Long transactionId) {
  Transaction toRet = transferDAO.get(transactionId);
  return Response.status(Status.OK).entity(toRet).build();

Now we bind this together using google Guice's ServletContextListener . To enable json support , you need to bind JacksonJsonProvider as well .
package com.javaroots.listeners;

import org.apache.log4j.Logger;
import org.codehaus.jackson.jaxrs.JacksonJsonProvider;

import com.javaroots.dao.TransferDAO;
import com.javaroots.dao.impl.TransferDAOMemoryImpl;
import com.javaroots.exception.RestExceptionMapper;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;

public class AppInitilizer extends GuiceServletContextListener {

 Logger log = Logger.getLogger(AppInitilizer.class);
 protected Injector getInjector() {
   return Guice.createInjector(new JerseyServletModule() {
             protected void configureServlets() {
                 // Configuring Jersey via Guice:


Now include this in web.xml .
<?xml version="1.0" encoding="ISO-8859-1" ?>

<web-app xmlns="" xmlns:xsi=""



Now you can access service at localhost:8080/{contextpath}/transactionservice

Post Comments And Suggestions !!!

Wednesday, 19 August 2015

Error In Starting of Mule App

Some times Mule app failed to start , throwing weird exception like this :
org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'mule'.
        at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
        at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)
        at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
        at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
        at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
        at org.apache.xerces.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
        at org.apache.xerces.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
        at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
        at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
        at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
        at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
        at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
        at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
        at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(
        at org.mule.config.spring.MuleApplicationContext.loadBeanDefinitions(
        at org.mule.config.spring.SpringRegistry.doInitialise(
        at org.mule.registry.AbstractRegistry.initialise(
        at org.mule.config.spring.SpringXmlConfigurationBuilder.createSpringRegistry(
        at org.mule.config.spring.SpringXmlConfigurationBuilder.doConfigure(
        at org.mule.context.DefaultMuleContextFactory.createMuleContext(
        at org.mule.module.launcher.application.DefaultMuleApplication.init(
        at org.mule.module.launcher.application.ApplicationWrapper.init(
        at org.mule.module.launcher.DefaultMuleDeployer.deploy(
        at org.mule.module.launcher.MuleDeploymentService.guardedDeploy(
        at org.mule.module.launcher.MuleDeploymentService.start(
        at org.mule.module.launcher.MuleContainer.start(
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.mule.module.reboot.MuleContainerWrapper.start(
        at org.tanukisoftware.wrapper.WrapperManager$
[28/01/2015 18:17:07 INFO  DefaultMuleApplication:197] App 'plum-slice-rest-api-3.3.4-SNAPSHOT' never started, nothing to dispose of
ERROR 2015-01-28 18:17:07,426 [WrapperListener_start_runner] org.mule.module.launcher.MuleDeploymentService:
+ Failed to deploy app                                     +
+ 'test', see below          +
The solution which you can try in this case pretty simple .
Just delete .mule folder
Post Comments and Suggestions !!

Thursday, 6 August 2015

Double Colon Operator in Java

Java 8 has introduced double colon (::) apart from lambda expressions. Let's see how does it work .

public class DoubleColonTest {
  interface MyInterface{
      public void interfaceMethod(String input);
  public static void staticmethod(String input)
    System.out.println(" static mymethod  " + input);
  public void method1(String input)
    System.out.println(" mymethod  " + input);
  public static void main(String[] args) {
    DoubleColonTest obj = new DoubleColonTest();
    MyInterface dd = obj::method1;
    dd.interfaceMethod(" test string ");
    MyInterface second = DoubleColonTest::staticmethod;
    second.interfaceMethod(" test static string ");

In this example , we have a functional interface with method name interfaceMethod , and we have a DoubleColonTest class which has two method which takes same parameters as interfaceMethod .Now this line :
MyInterface dd = obj::method1;
This line tells the compiler to create an implementation of MyInterface by applying the body of method1 defined in the DoubleColonTest class . Since this method is instance method , we need to use instance of class. This is called instance method reference .We can take static method reference also like this :
MyInterface second = DoubleColonTest::staticmethod;
So , now we can reference methods and reuse them again and again . We can also reference Constructor also , but we need to have a constructor which matches the interface method signature like this :
public DoubleColonTest(String in)
    System.out.println(" constructor  " + in);
Now to create an implementation of MyInterface , just need to write :
 MyInterface third = DoubleColonTest::new;
 third.interfaceMethod(" test string ");   
please post comments and suggestions !!!