Tuesday, 7 April 2015

Lambda Expression Example In Java

Java 8 added support for Lambda Expression . So what exactly are Lambda Expressions ?

Lambda Expressions are nothing but Anonymous Functions . Anonymous functions are methods which does not have any names , they make the code more concise and readable ,Suppose you want to sort a list of person based on their age , you can write following code using anonymous class syntax :
Collections.sort(list, new Comparator() {
   public int compare(Person p1, Person p2) {
    return (p1.getAge() > p2.getAge()) ? 1 : 0 ; 

Now with the help of lambda expressions , this code can be reduced to one single line of code :
 Collections.sort(list,(p1,p2 ) -> (p1.getAge() > p2.getAge()) ? 1 : 0 );
its syntax is : (${Parameters}) -> {${method body}}

1 ) If the method takes only one parameter , then we do not need to use parenthesis.
2 ) We do not need to specify the type of parameter , it will be inferred automatically by java . so we do not need to write (Person p1 , Person p2 ) instead of (p1,p2).
3 ) The Interface must be Functional Interface . A functional interface is a kind of interface which contains only one single abstract method .In this example , Collections.sort method takes a Comparator as parameter , Comparator Interface has only one single method , so you can directly implement it without specifying its name using lambda .
4 ) You can write method body with multiple statements also like this :
Collections.sort(list,(p1,p2 ) ->{
   if ( p1.getAge() > p2.getAge())
    return 1 ;
    return 0 ;
5 ) If you want to use variable declared in the enclosing method , you have to declare that as final .
6 ) You can create a Runnable using Lambda like this :
Runnable r = () -> System.out.println("Hello World !! ");
Hers's the complete java program example for Lamda Expressions in java .
package java8Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class LambdaTest {
 public static void main(String[] args) {
  List<Person> list = generateList();
  //try to sort with age using anonymous classes way 
  Collections.sort(list, new Comparator<Person>() {
   public int compare(Person p1, Person p2) {
    return (p1.getAge() > p2.getAge()) ? 1 : 0 ; 
                // method variable must be final to be used in lambda expression 
  final int x = 0 ;
                 //you can create a Runnable like this also using lambda expression
  //Runnable r = () -> System.out.println("thread running ");
  //sorting with Age using lambda expression  
  Collections.sort(list,(p1,p2 ) -> (p1.getAge() > p2.getAge()) ? 1 : 0 );
  Collections.sort(list,(p1,p2 ) ->{
   if ( p1.getAge() > p2.getAge())
    return 1 ;
    return 0 ;
  for(Person p : list)
   System.out.println(p.getName() + " " + p.getAge() + "  " + p.getSalary());
  Collections.sort(list,(p1,p2 ) -> (p1.getSalary() > p2.getSalary()) ? 1 : 0 );
  for(Person p : list)
   System.out.println(p.getName() + " " + p.getAge() + "  " + p.getSalary());
  Collections.sort(list,(p1,p2 ) -> p1.getName().compareTo(p2.getName()));
  for(Person p : list)
   System.out.println(p.getName() + " " + p.getAge() + "  " + p.getSalary());

 private static List<Person> generateList() {
  List<Person> mylist = new ArrayList<>();
  Person p1 = new Person();
  Person p2 = new Person();
  Person p3 = new Person();
  return mylist;


Post Comments And Suggestions !!!

Tuesday, 31 March 2015

How to Resolve Conflict In Git

Through a development life cycle when it comes to commit our whole day work and stuck in merge conflict without resolved/ No knowledge what went wrong in conflict makes our happiest day a dreadful night .

Here are few tips which can save your dreadful night :

Git merge Style

Suppose you are on master and merging development :
$ git merge development
Auto-merging hello.rb
CONFLICT (content): Merge conflict in hello.rb
Automatic merge failed; fix conflicts and then commit the result.
We would like to see what the merge conflict is. If we open up the file, we’ll see something like this:

#! /usr/bin/env ruby

def hello
<<<<<<< HEAD
  puts 'Hi Santosh'
  puts 'Hello Abhisehk'
>>>>>>> development

Both sides of the merge added content to this file, but some of the commits modified the file in the same place that caused this conflict. One helpful tool is git checkout with the ‘--conflict’ option. This will re-checkout the file again and replace the merge conflict markers. This can be useful if you want to reset the markers and try to resolve them again.

You can pass –conflict either diff3 merge (which is the default). If you pass it diff3, Git will use a slightly different version of conflict markers, not only giving you the “ours” and “theirs” versions, but also the “base” version inline to give you more context.

$ git checkout --conflict=diff3 hello.rb
Once we run that, the file will look like this instead:

#! /usr/bin/env ruby

def hello
<<<<<<< ours
  puts 'Hi Santosh'
||||||| base
  puts 'Hello Santosh'
  puts 'Hello Abhisehk'
>>>>>>> theirs

If you like this format, you can set it as the default for future merge conflicts by setting themerge.conflictstyle setting to diff3.
$ git config --global merge.conflictstyle diff3
Keep Njoying GIT !!!!

Thanks to Santosh for writing this post .

Monday, 30 March 2015

How to install CasperJS on windows

CasperJs is a javascript library written for phantomjs which is a headless browser . To install casperjs in windows , first you need to download phantomjs and set its exe file path in you path environment variable . after that download casperjs for windows , and set its batchbin directory path in your path enviornment variable .

You can check your installation by typing phantomjs and casperjs on your command windows . If you do not get 'Unrecognized command error ' then it means your installation is successful .

Now you might get following error if you try to run some javascript in casperjs .
Couldn't find nor compute phantom.casperPath, exiting.
To resolve this error , you need to insert following lines in bootsrap.js in your bin directory of casperjs .
var system = require('system');
var argsdeprecated = system.args;
phantom.args = argsdeprecated;
Now , try to run again , and you will not see this error .


Post Comments and Suggestions !!

Thursday, 29 January 2015

Top Build Automation Tools

Apache ANT :

Apache Ant uses build.xml file to describe build process and it is implemented in java . ANT first version released in 2000 and soon became one of the most popular build tool at that time .Ant was intended to be used in place of unix make process which was not platform independent. ANT is an abbreviation for Another Neat Tool . Ant has several tasks available which you can use according to your project's requirements and it is flexible enough , so that you can create your own custom tasks . The biggest drawback of ANT is the use of xml file , which might become complex and verbose .

Apache MAVEN :

Apache Maven is based on project object model also known as POM. The biggest different between Maven And Ant is , Maven allowed the dependency to be downloaded over the internet . In ANT , we have to included each and every dependency by ourselves , Maven reduced the burden . It is also uses the pom.xml file for describing the build process , but the structure is completely different from Ant's build.xml . It still has the same problem of bulky and large xml file in case of big projects .

Gradle :

Gradle has combined the features of Ant and Maven with its own Domain Specific Langauge based on Groovy. It does not uses xml for describing the build process . Gradle is slowly getting popular .


Buildr is based on Ruby's build system Rake, and uses Ruby as a scripting language. It provides greater flexibility as you can write your custom Ruby code before and after standard buildr targets .


Thursday, 8 January 2015

Java MultiThreading Interview Question

What would be the output of the following program ?

public class ThreadTest implements Runnable
 private Object obj=new Object();

 public static void main(String[] args)
  ThreadTest test = new ThreadTest();
  Thread t1 = new Thread(test);
  Thread t2 = new Thread(test);

 public void run()
   System.out.println("1 " + Thread.currentThread().getId());
   obj = new Object();
   System.out.println("2 " +Thread.currentThread().getId());

Answer : The lock will break. The reason is that each and every object has got its own Object Monitor. Modifying the object means we will have a new lock object with new monitor. In such a case, lock will break and cause all the threads in the entry set to acquire the monitor.

Thursday, 18 December 2014

How to Check For Null Payload in Mule XML

If we want to check in our flow , weather payload is null or not , we can do it using MULE Expression Language .
#[payload == null]
This was not working in MULE 3.1.1 , so we can try another expression like this :
#[payload is NullPayload]
But , this condition also threw and Exception like this :
org.mule.api.MessagingException: Execution of the expression "payload is NullPayload" failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: NullPayload
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:35)
 at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:43)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:43)
 at org.mule.processor.chain.DefaultMessageProcessorChain.doProcess(DefaultMessageProcessorChain.java:93)
 at org.mule.processor.chain.AbstractMessageProcessorChain.process(AbstractMessageProcessorChain.java:66)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:43)
 at org.mule.processor.AbstractInterceptingMessageProcessorBase.processNext(AbstractInterceptingMessageProcessorBase.java:105)
 at org.mule.interceptor.AbstractEnvelopeInterceptor.process(AbstractEnvelopeInterceptor.java:55)
 at org.mule.processor.AsyncInterceptingMessageProcessor.processNextTimed(AsyncInterceptingMessageProcessor.java:118)
 at org.mule.processor.AsyncInterceptingMessageProcessor$AsyncMessageProcessorWorker$1.process(AsyncInterceptingMessageProcessor.java:186)
 at org.mule.processor.AsyncInterceptingMessageProcessor$AsyncMessageProcessorWorker$1.process(AsyncInterceptingMessageProcessor.java:179)
 at org.mule.execution.ExecuteCallbackInterceptor.execute(ExecuteCallbackInterceptor.java:20)
 at org.mule.execution.HandleExceptionInterceptor.execute(HandleExceptionInterceptor.java:34)
 at org.mule.execution.HandleExceptionInterceptor.execute(HandleExceptionInterceptor.java:18)
 at org.mule.execution.BeginAndResolveTransactionInterceptor.execute(BeginAndResolveTransactionInterceptor.java:58)
 at org.mule.execution.ResolvePreviousTransactionInterceptor.execute(ResolvePreviousTransactionInterceptor.java:48)
 at org.mule.execution.SuspendXaTransactionInterceptor.execute(SuspendXaTransactionInterceptor.java:54)
 at org.mule.execution.ValidateTransactionalStateInterceptor.execute(ValidateTransactionalStateInterceptor.java:44)
 at org.mule.execution.IsolateCurrentTransactionInterceptor.execute(IsolateCurrentTransactionInterceptor.java:44)
 at org.mule.execution.ExternalTransactionInterceptor.execute(ExternalTransactionInterceptor.java:52)
 at org.mule.execution.RethrowExceptionInterceptor.execute(RethrowExceptionInterceptor.java:32)
 at org.mule.execution.RethrowExceptionInterceptor.execute(RethrowExceptionInterceptor.java:17)
 at org.mule.execution.TransactionalErrorHandlingExecutionTemplate.execute(TransactionalErrorHandlingExecutionTemplate.java:113)
 at org.mule.execution.TransactionalErrorHandlingExecutionTemplate.execute(TransactionalErrorHandlingExecutionTemplate.java:34)
 at org.mule.processor.AsyncInterceptingMessageProcessor$AsyncMessageProcessorWorker.doRun(AsyncInterceptingMessageProcessor.java:178)
 at org.mule.work.AbstractMuleEventWork.run(AbstractMuleEventWork.java:43)
 at org.mule.work.WorkerContext.run(WorkerContext.java:311)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
 at java.lang.Thread.run(Unknown Source)
Caused by: org.mule.api.expression.ExpressionRuntimeException: Execution of the expression "payload is NullPayload" failed.
 at org.mule.el.mvel.MVELExpressionLanguage.evaluateInternal(MVELExpressionLanguage.java:208)
 at org.mule.el.mvel.MVELExpressionLanguage.evaluate(MVELExpressionLanguage.java:169)
 at org.mule.expression.DefaultExpressionManager.evaluate(DefaultExpressionManager.java:234)
 at org.mule.expression.DefaultExpressionManager.evaluateBoolean(DefaultExpressionManager.java:361)
 at org.mule.routing.filters.ExpressionFilter.accept(ExpressionFilter.java:127)
 at org.mule.routing.ChoiceRouter.selectProcessors(ChoiceRouter.java:35)
 at org.mule.routing.AbstractSelectiveRouter.process(AbstractSelectiveRouter.java:194)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
 at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:43)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:43)
 at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:27)
 at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:43)
 ... 23 more
Caused by: [Error: could not access: NullPayload; in class: null]
[Near : {... Unknown ....}]
[Line: 1, Column: 0]
 at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getBeanProperty(ReflectiveAccessorOptimizer.java:611)
 at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getBeanPropertyAO(ReflectiveAccessorOptimizer.java:439)
 at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.compileGetChain(ReflectiveAccessorOptimizer.java:353)
To resolve this , you have to tweak the expression a little bit like this :
#[payload is org.mule.transport.NullPayload]
Post Comments And Suggestions !!


Thursday, 20 November 2014

How To Get Client Operating System Name IN ROR

In the world of increasing web sites in a fast pace , at times we need to get the clients OS details to execute some script in clients machine, or know what is the OS/Web browser/Client Details used by client.

When ever a client accesses your website and makes a request, Browser sends the details of the client in as an WEBHTTP OBJECT.

HTTP_USER_AGENT request header contains the information about client .

To get this information in rails we need to write following code .

we create a around filter/action to and paste it in application controller so that it keeps the track of every request.

def get_operating_system
  if request.env['HTTP_USER_AGENT'].downcase.match(/mac/i)
  elsif request.env['HTTP_USER_AGENT'].downcase.match(/windows/i)
  elsif request.env['HTTP_USER_AGENT'].downcase.match(/linux/i)
  elsif request.env['HTTP_USER_AGENT'].downcase.match(/unix/i)
Thanks to Santosh for writing this post .