Saturday, April 25, 2015

Ant Cheat Sheet

This post list some of the commonly used ant commands and shortcuts.

Test if ant is installed
$ant -version
Ant is a command-line tool so it must be on the path to be used. If Ant is installed, above command will return version details otherwise it will say that ant command is not found (i.e. Ant is not installed).

It gives below response when I run it on my Mac:
Apache Ant(TM) version 1.9.2 compiled on July 8 2013

Running ant target(s)
$ant                                     //runs default target
$ant compile                       //runs compile target
$ant <target1> <target2>    //runs multiple targets

Generate verbose log during build
$ant -verbose        //runs default target in verbose mode
$ant <target> -verbose
$ant <target> -v   // v is shortcut for verbose
Ant produces verbose log when invoked with -verbose (or -v) parameter. This is useful to figure out what's going out during build and specially when build fails.

Generate debug log during build
$ant -debug                 //runs default target in debug mode
Debug prints more log information than verbose. This option prints lot more low-level details along with verbose details.
$ant -quiet                  //to see nothing but errors and final build status message
$ant -keep-going        //tells ant to try to recover from failure

List all targets
$ant -projecthelp        //or -p
$ant -p -verbose         // list sub-targets as well
Lists all the targets provided by build file. Ant list only public targets with optional description attribute. To see optional targets also along with main targets run above command with -verbose.

Pass a property dynamically

$ant execute -Dproperty=value
Passes a key value (property) pair to the ant build. This will override if the property already exist in the build or config file.

Get build sequence
Target dependency is transitive. So if the build file is quite huge then knowing the dependency becomes quite difficult. To get it, I often run the build in verbose mode and then grep for the given String.

$ant -v main | grep "Complete build sequence is"
Complete build sequence is [clean, compile, execute, main, ]

Help
$ant -help     //or -h
If you don't remember this cheat sheet, just ask ant to help. It will give all the options which ant supports. I have covered some of them here, but some other useful options like providing your own build file other than build.xml etc are not covered here.



    

Tuesday, April 14, 2015

Functional Interfaces in Java 8

This post compliments the previous post where I have discussed about Lambda Expression, link. To unleash the power of lambda, a good understanding of functional interface is must. Let's briefly cover it:

Functional Interface

Functional Interfaces are those Interfaces in Java which has only one abstract method. Interfaces having single method (like Runnable, Callable, Comparable etc) existed in Java even before version 8. It's just that this new term was coined in context of Lamda Expression.

Functional interfaces are pre-condition for Lambda expression. Lambda expression allows you to provide the implementation of the method inline as an anonymous implementation of the interface.   Before Java 8, programmers used to provide implementation of functional interfaces using Anonymous class (which let you declare and instantiate the class at same time). Below is mostly commonly seen way to implement a Runnable task. 

  Runnable task = new Runnable(){
    public void run(){
        //implementation...bla bla.
  }
};

If interface is NOT functional, implementing the interface or providing anonymous implementation as shown above are two options. But if there is just one abstract method in the interface, Java 8 provides a more succinct and less verbose style to provide implementation. Java also introduces an optional annotation to mark an interface as functional. 


@FunctionalInterface
public interface MyFunctionalIf {
public String doSomething(String);

}

Annotation is used to indicate that the interface is intended to be functional interface. It's not mandatory to use the annotation but definitely a good practice. This annotation will also prevent you to accidentally add another method and break the functional contract of having just a single method. One important point to keep in mind is that default and static methods don't break the functional contract. 
Above interface can be used by implementing it in a concrete class or by providing ad-hoc implementation using anonymous class as shown for Runnable. 

Implementing Functional Interface using Lambdas

Functions were not first class citizen (before Java 8) and you need to have a handle of object to call/use method. Now let's see how lambda changes the implementation of functional interfaces:

Runnable lambdaTask = () -> { //implementation  };
lambdaTask.run();  //using lambda

MyFunctionalIf myFunctionalIf = (String message) ->  "hello "+ message;
myFunctionalIf.doSomething("Sid");   //using lambda

                                                                                   
Now, look how cleaner the functional implementation of the interfaces look. It's very concise, flexible and re-usable.

Please note that in second case, the curly brace as well as return clause is missing (both can be removed if there is only one line in the method body. Even type in argument is optional, so you can ignore String in above lambda expression. Notice that the name of the method is missing in lambda so it is also called as anonymous method

Default Method

Now interfaces can also provide a default methods. Obviously, functional interfaces can also have any number of default methods. You just need to add default keyword in method definition.

List<> interface adds a sort method so that you can sort a list by calling sort method on its instance instead of calling sort method from Collections utility class.

default void sort(Comparator<? super E> c) {
     //implementation 
}

In-built Functional Interfaces Added In Java 8

Imagine creating your own multiple functional interfaces. But, Java helps programmers by providing some reusable functional interfaces out of the box. 

Java designers have created a separate package for same, java.util.funtion.

So do check this package before creating your own functional interfaces. Chances are high that you will find one matching your needs.

---
keep coding !!!

Sunday, March 29, 2015

Euclid's GCD Algorithm

Before turning our head to Euclid's algorithm for calculating GCD, let's cover the more fundamental approach to calculate GCD.

GCD (Greatest Common Divisor)

GCD of two integers A and B is the largest integer that divides them both without a remainder. It is also known as GCF(Greatest Common Factor), HCF(Highest Common Factor) and GCM(Greatest Common Measure).

So GCD(A, B) will be between 1 and min(A, B), both inclusive. So it can be implemented as shown below:

 public int gcd(int a, int b) {
   for (int i = Math.min(a, b); i > 1; i--) {
     if (a % i == 0 && b % i == 0) {
       return i;
     }
   }
   return 1;
 }

Euclid's Algorithm

Above algorithm is not very efficient, as in worst case it can end up doing min(a,b) modulo operations. Euclid's or Euclidian algorithm is an efficient algorithm for calculating GCD of two numbers. And due to its efficiency and simplicity, it is one of the oldest numerical algorithms which is still in use. This algorithm iterates over the two numbers until the remainder is 0. 

To calculate GCD,
Express first in terms of the second number i.e. A = B*K + C
Now repeat the operation for K and C (until C is 0)
The last non-zero remainder is GCD. 

GCD(18,12) => 18 = 12*1 + 6
GCD(6,1)    =>  6 = 1*6 + 0
GCD = 6

Recurrence relation would be:
GCD(A,0) = A
GCD(A,B) = GCD(B, A mod B), for B>0

Implementation

Recursive implementation is quite trivial:

public int euclidGcd(int a, int b){
  if(b ==0 ) return a;
  return euclidGcd(b, a%b);
}

--
keep coding !!!

Saturday, March 28, 2015

Lambda Expression in Java 8

Let's go functional!

Lambda Expression (Closure or Anonymous method) is one of the most important additions to Java 8.  In fact, it's the most incredible additions to language in its history; it is going to change the way we write programs in Java.  With this new feature, Java adds one of the modern programming technique, Functional Programming.

This is useful for Functional Interfaces (the interface that requires exactly one method to be implemented). Runnable, Callable, Comparable and other interfaces which just have a single method are called functional interfaces. You can even define your own interface with a single method to unleash the power of Lambdas.

Syntax of Lambda

Lambda consists of 3 parts :
  1. Parenthesized set of parameters
  2. Arrow sign ( -> )
  3. Body in form of single expression or a block 
i.e. (Parameter1 p1, Parameter2 p2)            ->                           { }
       (parameters)                                   (arrow sign)          (method body)

Properties:
  • It doesn't have an explicit name for the method, so it's called an anonymous method as well
  • It can throw Exceptions
  • It's more like a method (and not a class), it has a list of parameter, body and return type
  • It can be passed as an argument to a method and can be stored as a value in a variable

Runnable Implementation without Lambdas

Before going all out on Lambda. Let's see how these interfaces get implemented without it.

Approach 1: Implement the interface

public class MyRunnableImpl implements Runnable{
     @override
     public void run(){
         //TODO: Implementation
     }
}

Approach 2: Using anonymous (inner) class
   
Runnable task = new Runnable(){
    public void run(){
       //TODO: Implementation
   }
};

Approach 2 is better than first but still, it's quite verbose and there is hardly any scope of reusability.

Implementing functional interfaces through Lambda

The compiler knows beforehand that the Runnable interface has only one method to be implemented. So this lack of ambiguity around which method needs to be implemented helps in making the Runnable implementation more compact and efficient using lambdas. 

So using Lambda; above code can be replaced as :

Runnable task = () -> System.out.println("inside run method");
or 
Runnable task = () -> { System.out.println("inside run method"); };

And on similar lines you can implement Callable as well :

Callable<Integer> task = () -> {
       Random r = new Random(101);
       return r.nextInt(101);
};

If the method takes some argument, then they get passed inside parentheses. Let's take case of Comparator interface:


Comparator<String> c = (String a, String b) -> { return a.compareTo(b); };


Before version 8, the lowest level of abstraction in Java was classes. Functions were not treated as the first-class citizen as you need to have an object handle to use functions (functions don't exist without object). But functions are as valuable and important as objects and classes. Programming languages with first-class functions let you find more opportunities for abstraction which means your code is smaller, lighter, more reusable and scalable.

Related Post: Functional Interfaces

---
keep coding !!!

Saturday, February 28, 2015

Understanding JAVA EE Interceptors

Interceptors are used to implement orthogonal or cross-cutting concerns such as logging, auditing, profiling etc in Java EE applications. In this aspect, it is similar to aspect-oriented programming (AOP).

In Java EE 5, Interceptors were part of EBJs, but in later versions, Interceptors have evolved into a new specification of its own. Interceptors were split into an individual spec in Java EE 7 (Interceptors 1.2) and are part of Context and Dependency Injection(CDI) specification.  They can be applied to any managed classes/beans like EJBs, Servlets, SOAP and RESTful web services. Managed Beans are container-managed objects (unlike Java Beans or POJOs which run inside JVM).  In Java EE 7, Dependency Injection (JSR 330) and  CDI (JSR 299) are merged. You can refer to managed beans as CDI bean as well. These managed beans are injectable and interceptable.

In this post, I will be using terms CDI bean and managed bean interchangeably.

Interceptors

Interceptor is a class whose methods are invoked when methods on a target class are invoked. And this invocation of interceptors methods is performed by the container. Obviously, this would be possible if the target class and the interceptors both are managed by the container.  This is possible because beans managed by containers (servlet or EJB) provides the ability to intercept method invocation through interceptors. 


Interceptors are powerful means to decouple technical concerns from business logic. And it uses strongly typed annotations to achieve it instead of String-based identifiers. This way usage of XML descriptors is minimized. Interceptors use a mandatory deployment descriptor, bean.xml. This is required so that CDI is able to discover the bean from the classpath.

Below are interceptor metadata annotations (from javax.interceptor ):
  • @AroundConstruct associates with the constructor of the target class
  • @AroundInvoke associates with a business method and gets called while entering and exiting
  • @AroundTimeout associates with timeout methods
  • @PostConstruct & @PreDestroy on corresponding lifecycle events of the target class

Using Interceptors

Interceptors, intercept a particular target class so they have the same life cycle as that of the target class. Target class can have any number of associated interceptors.

Intercepting a REST Service

Interceptors can intercept any managed bean; so it can intercept servlet, REST entry point, EJB etc. I will be showing an example of intercepting a REST service.

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;

/**
 * Interface for logging/auditing JAX-RS requests
 *
 */
@Inherited
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Auditor {
}



import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
/**
 * CDI/Managed bean which intecepts REST API
 * Add @Interceptors(RestAuditor.class) to the target class/method
 *
 */
@Interceptor
@Auditor
public class RestAuditor {
 @AroundInvoke
 public Object intercept(InvocationContext context) throws Exception {
  //context.getMethod().getName())
               // audit/log the request
  return context.proceed();
  //control comes back after target method execution 
 }
}


<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
   <interceptors>
        <class>RestAuditor</class>  <!--fully qualified class name -->
    </interceptors>
</beans>

So interceptor definition and the declaration of the interceptor in bean.xml completes the interceptor part. Now next step is to use above defined interceptor on a REST service. Please note that the intercept method will be called before actually calling the REST method and then again once REST method is complete, the control comes back. So the request as well response both can be logged in the intercept(..) method. Using the interceptor is quite trivial, we just need to annotate the REST class as shown below :

@Path("/sample")
@ApplicationScoped
@Interceptors(RestAuditor.class)
public class SampleRestService implements Serializable {  
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public boolean getLogs() {
  boolean resp = true;
  return resp;
 }
}

That's it!

Important Points

  • If the application contains several jar files and you want to enable CDI across the application then you need to have beans.xml in each jar. Only then CDI will trigger bean discovery for each jar. 
  • Interceptors can be applied to method as well as class level. If you want to intercept a specific method then put the annotation at method level only (NOT at class level as shown above).