Monday 8 December 2014

Lambda Expressions in Java 8

Lambda expressions are a new and important feature included in Java SE 8.  A lambda expression provides a way to represent one method interface using an expression.
Lambda expression is like a method, it provides a list of formal parameters and a body (which can be an expression or a block of code) expressed in terms of those parameters.
 Lambda expressions also improve the Collection libraries making it easier to iterate through, filter, and extract data from a Collection. In addition, new concurrency features improve performance in multicore environments.

Anonymous Inner Class:
In Java, anonymous inner classes give you a way to implement classes that may occur only once in an application.
For example, in a standard Swing or SWT application a number of event handlers are required for keyboard and mouse etc.. events. Rather than writing a separate event-handling class for each event, you can write something like this.

 JButton testButton = new JButton("Button");
 testButton.addActionListener(new ActionListener(){
 @Override public void actionPerformed(ActionEvent ae){
     System.out.println("Action Performed in Anonymous Class");

Functional Interfaces:
The ActionListener example is an interface with only one method. With Java SE 8, an interface that follows this pattern is known as a "Functional Interface".

package java.awt.event;
import java.util.EventListener;
public interface ActionListener extends EventListener {    
   public void actionPerformed(ActionEvent e);

Functional Interfaces are leveraged for use with lambda expressions.

Lambda Expression Syntax:
Lambda expressions address the problem of anonymous inner classes by converting five lines of code into a single statement. This simple horizontal solution solves the "vertical problem" presented by inner classes.

A lambda expression is composed of three parts.

The body can be either a single expression or a statement block.
In the single expression form, the body is simply evaluated and returned.
In the block form, the body is evaluated like a method body and a return statement returns control to the caller of the anonymous method. The break and continue keywords are illegal at the top level, but are permitted within loops. If the body produces a result, every control path must return something or throw an exception.


(int x, int y) -> x * y // 1st

() -> true              // 2nd 

(String s) -> { System.out.println(s); } // 3nd

  1. 1st: The first expression takes two integer arguments, x and y, and return x*y. 
  2. 2nd: It don't take any argument, but return false.
  3. 3rd: Prints the String into console.
Lambda Function Example with Functional Interface:

1. Runnable: You can write a Runnable using lambdas, See below code:

public class RunnableTest {
  public static void main(String[] args) {
    System.out.println("**** Runnable Lambda Test ****");
    // Anonymous Runnable
    Runnable runnableOld = new Runnable(){      
      public void run(){
        System.out.println("Hello world OLD!");
    // Lambda Runnable
    Runnable runnableNew = () -> System.out.println("Hello world NEW!");
    // Run it;;    

As you can see Lambda function converts five lines of code into one statement.

2. Comparator: In Java, the Comparator class is used for sorting collections.
In the following example, an ArrayList consisting of Person objects is sorted based on surName. The following are the fields included in the Person class.

public class Person {
   private String firstName;
   private String surName;
   private int age;

Comparing using Comparator.

public class LembdaComparator { 
  public static void main(String[] args) {   
    List<Person> personList = Person.getDummyList(); // For example 
    // Sort with Inner Class way
    Collections.sort(personList, new Comparator<Person>(){
      public int compare(Person p1, Person p2){
        return p1.getSurName().compareTo(p2.getSurName());
    // Use Lambda instead
    Collections.sort(personList, (Person p1, Person p2) -> p1.getSurName().compareTo(p2.getSurName()));   

The following code will prints all list entries in the console using Lambdas:

/* sorts all elements in a collection using a lambda expression as comparator */
List names = Arrays.asList( "Test", "Test1", "Test2", "Test3" );
names.forEach( s -> System.out.println( s ) );

3. Listeners: example of  ActionListener.

public class ListenerClass {
  public static void main(String[] args) {        
    JButton testButton = new JButton("Button");
    // using anonymous class
    testButton.addActionListener(new ActionListener(){
    @Override public void actionPerformed(ActionEvent ae){
        System.out.println("Action perfromed anonymous Class");
    // Using Lemnbda Expression 
    testButton.addActionListener(e -> System.out.println("Action perfromed by Lambda Listner"));

The java.util.function Package:
Functional interfaces provide target types for lambda expressions and method references.

 1. Function<T,R>this is a functional interface whose sole purpose is to return any result by working on a single input argument. It accepts an argument of type T and returns a result of type R, by applying specified logic on the input via the apply method.

// convert centigrade to fahrenheit
Function<Integer,Double> centigradeToFahrenheitInt = x -> new Double((x*9/5)+32);
// String to an integer
Function<String, Integer> stringToInt = x -> Integer.valueOf(x);
System.out.println("Centigrade to Fahrenheit: " + centigradeToFahrenheitInt.apply(centigrade))
System.out.println(" String to Int: " + stringToInt.apply("4"));

2. BiFunction<T,U,R>BiFunction represents a function that accepts two arguments and produces a result. This is the two-arity specialization of Function.

/* functions with two input parameters and one output can be implemented easily using lambdas */
BiFunction addition = ( x, y ) -> x * y;
System.out.println( "Multiplication of 5 and 7 is: " + addition.apply( 5, 7 ) );

3. Predicate<T>:  In mathematics, a predicate is commonly understood to be a Boolean-valued function P: X? {true, false}, called the predicate on X.
In java 8, Predicate a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. So, where you think, you can use these true/false returning functions in day to day programming?
You can use them anywhere where you need to evaluate a condition on group/collection of similar objects such that evaluation can result either in true or false e.g.

  1. Find all children borned after a particular date
  2.  Pizzas ordered a specific time
  3.  Employees greater than certain age and so on..

Employee Class have following properties: 

public class Employee {     
   private Integer id;
   private Integer age;
   private String gender;
   private String firstName;
   private String lastName;

Some predicates on Employee Class can be:

a. All Employees who are male and age more than 18

public static Predicate<Employee> isAdultMale() {
    return p -> p.getAge() > 18 && p.getGender().equalsIgnoreCase("M");

b.  All Employees whose age is more than a given age

public static Predicate<Employee> isAgeMoreThan(Integer age) {
    return p -> p.getAge() > age;

Created another utility method filterEmployees() for using Predicate:

// Use Predicate
public static List<Employee> filterEmployees (List<Employee> empList, Predicate<Employee> predicate) {
      return predicate ).collect(Collectors.<Employee>toList());

Note: BiPredicate represents a predicate which is a boolean-valued function of two arguments.

4. Supplier<T>Suppliers represent a function that accepts no arguments and produce a result of some arbitrary type.

a. Supplier referencing a constructor method:

Supplier<Employee> empSupplier = Employee::new;
Employee emp = empSupplier.get();

b. Supplier referencing a static method:

Supplier<Employee> empSupplier = EmployeeFactory::produceEmp;
Employee emp = empSupplier.get();

class EmployeeFactory {
  public static Employee produceEmp() {
    return new Employee();

c. Supplier referencing an instance method:

Supplier<Employee> empSupplier = this::produceEmp;
Employee emp = empSupplier.get();

private Employee produceEmp(){
  return new Employee();

5. Consumer<T> The Consumer accepts a single argument but does not return any result. This is mostly used to perform operations on the arguments such as persisting the employees, invoking house keeping operations, emailing newsletters etc.

a. Simple consumer: 

Consumer<Employee> empConsumer = (e) -> System.out.println("Username: " 
   + e.getFirstName());

b. Consumer applied to a stream: 

Consumer<Employee> consumer = (Employee emp) -> System.out.println("Name:"+emp.firstName +" and Age:"+emp.age);

6. UnaryOperator<T>: this extends a Function acts only on same types. So, if we know that both the input and output types are the same, we could use UnaryOperator instead of Function.

UnaryOperator<String> toLowerUsingUnary = (s) -> s.toLowerCase();
String inLowerString = toLowerUsingUnary.apply("HELLO");

For more deatils See:

Monday 24 November 2014

Eclipse Preference Scope

The Eclipse preferences supports for storing data between application restarts. Preferences are stored as key / value pairs. The key is a String. The value can be a boolean, String, int... etc.

Configuration scope: Preferences stored in this scope are shared by all workspaces that are launched using a particular configuration of Eclipse plug-ins. On a single-user installation, this serves to capture preferences that are common to all workspaces launched by that user. On a multi-user installation, these preferences are shared by all users of the configuration.

Instance scope: Preferences in this scope are specific to a single Eclipse workspace. The old API method getPluginPreferences on Plugin stores its preferences at this scope.

Default scope:. This scope is not stored on disk at all but can be used to store default values for all your keys. When values are not found in other scopes, the default scope is consulted last to provide reasonable default values.

BundleDefaultsScope: Similar to the default scope, these values are not written to disk. They are however read from a particular bundle's "preferences.ini" file.

Project scope: This scope stores values that are specific to a single project in your workspace, such as code formatter and compiler settings. Note that this scope is provided by the org.eclipse.core.resources plug-in, which is not included in the Eclipse Rich Client Platform. This scope will not exist in applications that don’t explicitly include the resources plug-in.

See for more details:

  1. ConfigurationScope
  2. InstanceScope
  3. DefaultScope
  4. ProjectScope

Monday 29 September 2014

Eclipse Plugin Version Numbering

Eclipse, version numbers are composed of four (4) segments: 3 integers and a string respectively named major.minor.service.qualifier.

Each segment captures a different intent:
  • the major segment indicates breakage in the API
  • the minor segment indicates "externally visible" changes
  • the service segment indicates bug fixes and the change of development stream.
  • the qualifier segment indicates a particular build
When to change the major segment:
The major segment number must be increased when a plug-in makes breaking changes to its API. When the major segment is changed the minor and service segments are reset to 0.
Example: From the version 1.3.6, an incompatible change would lead to 2.0.0. 

When to change the minor segment:
The minor segment number must be incremented when a plug-in changes in an "externally visible" way. Examples of externally visible changes include binary compatible API changes, significant performance changes, major code rework, etc. Another way to know when this version number should be changed is by exclusion: it should indicate changes that are neither bug fixes (indicated by the service segment) nor breaking API changes (indicated by the major segment). When the minor segment is changed, the service segment is reset to 0.
Example: From the version 1.3.6, a minor change would lead to 1.4.0.

When to change the service segment:
The service segment number must be incremented whenever there have been changes to a plug-in between releases that are not visible in its API. For example, a bug has been fixed in the code, the plug-in manifest has changed, documentation has changed, compiler settings have changed. In general, if that change happens in a service (a.k.a. maintenance) release, then 1 is added. If it happens for the next official release, 100 has to be added. As a result, the service segment number for official releases normally ends with a zero (0, 100, 200, etc.). If that is not true for whatever reason, then one must not add 100 but instead set the service segment number to the next number that is divisible by 100, so that the normal numbering scheme is restored. This practice makes it easy to manage one line of descent after a release and still guarantee that plug-ins coming in the next release will have a higher version number than ones from maintenance releases (thus enabling the usage of update manager from maintenance releases to the new releases).
Example: At the end of the development stream N, the version of the plug-in P is 2.4.0. When P makes its first change in the development stream N+1, then the version should be changed to 2.4.100. If P version 2.4.0 needs to receive a bug fix in the maintenance stream started from N, then its version number will be 2.4.1.

First development stream
 - 1.0.0

Second development stream
 - 1.0.100 (indicates a bug fix)
 - 1.1.0 (a new API has been introduced)
 The plug-in ships as 1.1.0

Third development stream
 - 1.1.100 (indicates a bug fix)
 - 2.0.0 (indicates a breaking change)
 The plug-in ships as 2.0.0

Maintenance stream after 1.1.0
 - 1.1.1
 The plug-in ships as 1.1.1

Plug-ins with no API:
There are certain kinds of plug-ins that have no API, and therefore would never evolve more than their service segment according to the above rules. For these plug-ins, the version number can be evolved in sync with another plug-in they are associated with. Note that since these plug-ins do not contain any API, they are generally only explicitly required by plug-ins they are closely associated with anyway.

In particular, a source/test/documentation plug-in that has changes in the current stream should evolve its version number in sync with the plug-in(s) it is providing source/test/documentation for. A fragment with no API should evolve its version number in sync with its host plug-in.

Versioning plug-ins that wrap external libraries:
The version range guidelines above are only effective if the required bundle or feature follows the Eclipse version number evolution guidelines outlined in this document. When specifying a dependency on third party libraries (e.g. those from Orbit), be sure you understand the semantics of that library's version numbers, and specify your version range accordingly. In the absence of any well defined version evolution semantics, you should just specify the version number you require as a lower bound.

Example: JFace requires a third party library wrapped in bundle, and is compiled against version 3.8.1 of that bundle. It should specify its dependency as follows: Require-Bundle:;bundle-version="3.8.1"

Friday 16 May 2014

Add Automatic generated build ID in about dialog using Tycho (Maven)

Follow the following Steps to generate Build-ID Automatically form Tycho:

1. Open your plugin.xml which have org.eclipse.core.runtime.products Extension add or replace following properties.

2. In same plugin open MANIFEST.MF and add following lines.
Bundle-Localization: plugin
This allows you to use

3. Create or open your and add following add your about dialog as below.
productBlurb=Eclipse Platform\n\
Version: {1}\n\
Build id: {0}\n\
(c) Copyright Eclipse contributors and others 2000, 2014. \
..... your thing\n

4. Now create a about.mappings file if you already have change it like below.

5. Now open your pom file and add below settings.
    <maven .build.timestamp.format="">yyyyMMdd-HHmm</maven>
    <releasename>5.0.0 RC0</releasename>


6. Run the build now you will get product's about dialog with automatic generated Build-ID.

Wednesday 16 April 2014

Why is char[] preferred over String for passwords?

Strings are immutable. That means once you've created the string, if another process can dump memory, there's no way you can free the data before GC kicks in.
With an array, you can explicitly wipe the data after you're done with it: you can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.
It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.
 <script type="text/javascript">
 var d = new Date();
 var time = d.getHours();
 if (time < 10) {
 document.write("<b>Good morning</b>");
 } else {
 document.write("<b>Good day</b>");