Friday, March 31, 2017

Useful Eclipse IDE Tips

INTRODUCTION

The aim of this post is to share some of the useful tips for Eclipse IDE. Hope it can be helpful during development of your project.

1. how to increase eclipse console size

  1. Go to Preferences
  2. Select Console on Run/Debug
  3. Enter the value 1000000 for 'Console buffer size'
  4. Click Apply & Ok.
  5. Now you can see more logs in the console.

2. how to create java code templates in eclipse

Consider I would like to add my name, Ranjith Sekar, as an author of the java file and the current date is the date of creation of the file.
  1. Go to Preferences in Eclipse
  2. Select Java->Code Style->Code Templates
  3. Expand the Code and select 'New Java File'
  4. The default would be as below
${filecomment}
${package_declaration}

${typecomment}
${type_declaration}

  1. Click Edit and Enter as below
${filecomment}
${package_declaration}
/**
* @author Ranjith Sekar(java2ranjith@gmail.com)
* @since ${date}
*/
${typecomment}
${type_declaration}

  1. Click Ok
  2. Create a new Java file called MyNewClass.java
  3. Your class would be created as below
package java2ranjith.thiskeyword;
/**
* @author Ranjith Sekar(java2ranjith@gmail.com)
* @since Jun 26, 2014
*/
public class MyJavaClass {

}

3. how to filter .class files in eclipse file search

  1. Select your project in eclipse and right click and select Properties.
  2. Go to Resource->Resource Filters
  3. Click Add
  4. Select 'Exclude All' in Filter Type.
  5. Select 'All Children' in Apply to
  6. Type *.class into the File and Folder Attributes (Name - Matches) and click OK.
  7. The Project will be rebuilt automatically.
Now try to search any java file where you couldn't find any .class file of those.

Thursday, March 30, 2017

Builder Design Pattern Using Java 8

INTRODUCTION

Builder design pattern is mainly focused on creating a complex object. Creation of complex object will be done by the sequence of smaller steps, i.e splitting the complex logic into multiple simple units. These simple units can be reused again. The whole complex object creation will be controlled by a controller/builder.
In this article, we are going to implementation the Builder Design Pattern using java before and after the version Java 8.

USECASE

Assembling a bike with its components like Engine, Wheel, and Gear etc.,

IMPLEMENTATION - BEFORE JAVA 8

Assembling a bike will have many activities like assembling the engine, wheel, estimating the cost and finally naming the bike etc,.
Lets us create Model Class - Bike.
public class Bike {
 private String name;
 private String wheelType;
 private String engineType;
 private int cost;
 //getters and setters
}


Create Builder interface with the list of activities.

public interface BikeBuilder {
 Void setName();
 void assembleEngine();
 void assembleWheel();
 void estimateCost();
 Bike getBike();
}

Now implement the BikeBuilder and create different bikes like HeroBike, RoyalEnfield Bike.

public class RoyalEnfield implements BikeBuilder {

 private Bike bike;

 RoyalEnfield() {
 bike = new Bike();
 }

 public void assembleWheel() {
 bike.setWheelType("Spoke");
 }

 public void estimateCost() {
 bike.setCost(170000);
 }

 public void assembleEngine() {
 bike.setEngineType("Diesel");
 }

 public void setName() {
 bike.setName("RoyalEnfield");
 }

 public Bike getBike() {
 return bike;
 }
}

Now time to test the builder pattern.

public class BuilderPatternMain {

public static void main(String[] args) {

 BikeBuilder heroBikeBuilder = new HeroBike();
 heroBikeBuilder.assembleWheel();
 heroBikeBuilder.assembleEngine();
 heroBikeBuilder.estimateCost();
 heroBikeBuilder.setName();

 // Get Hero Bike
 System.out.println(heroBikeBuilder.getBike().toString());

 BikeBuilder enfieldBike = new RoyalEnfield();
 enfieldBike.assembleWheel();
 enfieldBike.assembleEngine();
 enfieldBike.estimateCost();
 enfieldBike.setName();

 // Get Royal Enfield Bike
 System.out.println("\n" + enfieldBike.getBike().toString());
 }
}

IMPLEMENTATION - USING JAVA 8

New Java 8 Features like Lambda Expression, Streams, Method References etc., helps the developers to develop clear, easy understanding and simple code.
A separate package has been introduced for Functional Interfaces (java.util.function) as part of Java 8 release.
Here I am going to use Consumer Interface from java.util.function package ( to know more about Consumer Interface check out Functional Interface article).
No change in Bike.java  class.
  1. Return the HeroBike/RoyalEnfield object for assembleEngine(), assembleWheel(), estimateCost() and setName() methods.
  2. Modify the getBike() method, so that it will accept the Consumer object as an argument and also creates the HeroBike/RoyalEnfield object.

import java.util.function.Consumer;

public class HeroBike {

 private static Bike bike;

 public HeroBike assembleEngine() {
   bike.setEngineType("Petrol");
   return this;
 }

 public HeroBike assembleWheel() {
   bike.setWheelType("Alloy");
   return this;
 }

 public HeroBike estimateCost() {
   bike.setCost(50000);
   return this;
 }

 public HeroBike setName() {
   bike.setName("Hero");
   return this;
 }

 public Bike getBike(Consumer<HeroBike> heroBike) {
   bike = new Bike();

   HeroBike newHeroBike = new HeroBike();
   heroBike.accept(newHeroBike);

   return bike;
}
}

Check out below how easy is to implement the Builder Pattern using java 8.

public class BuilderPatternMainJava8 {

 public static void main(String[] args) {
   HeroBike heroBike = new HeroBike();
   System.out.println(heroBike.getBike(
     bike -> bike.assembleEngine()
                  .assembleWheel()
                  .estimateCost()
                  .setName())
                  .toString());

   RoyalEnfield royalEnfield = new RoyalEnfield();
   System.out.println("\n" + royalEnfield.getBike(
     bike -> bike.assembleEngine()
                 .assembleWheel()
                 .estimateCost()
                 .setName())
                 .toString());
 }
}

Here we have eliminated calling the method from the object again and again. Also, makes the code clear and easy understanding.

Hope this example clarifies the Builder Design Pattern Using Java 8. Please share your comments below.
Happy Knowledge Sharing!!!

Wednesday, March 29, 2017

Lateral view explode() function in Hive

INTRODUCTION

In this article, we are going see how lateral view explode() function works in Hive. The explode() function will help to display the array or list of data into individual items in the RDBMS.

I am going to cover the below topics in this article.
  1. explode() function
  2. Lateral view explode function
  3. Use explode() function for a UDF returns List
  4. Use explode() function for a UDF returns Map
  5. Lateral view explode function for UDF
For all the below examples, I have used the table STUDENT table from my previous post on how to insert values into hive table directly

1. explode() function

If we wanted to display the subject of a student into a separate line, we can use explode function as below.

Query
SELECT explode(student) from student where id='100';

Output
Mathematics
Biology
Physics
Chemistry

2. Lateral View explode() function

If we wanted to display the subject along with the student id, we can use explode function with the lateral view.
Query
hive> SELECT s.id, ex.subject
   > FROM student s
   > LATERAL VIEW explode(subjects) ex
   > AS subject;

Output

Note: soon will cover the other topics.

Wednesday, March 22, 2017

Command Design Pattern in Java

INTRODUCTION

Command design pattern is categorized under Behavioral Design Pattern. Encapsulate the request and pass it to appropriate processor to process the request. It provides callback mechanism, so that we can get the output for the request.

KEY ENTITIES

  1. Command - is the one who will have the definition of the action.
  2. Invoker - is the one who will receive the request but don't know how to process the request. It uses the command to initiate the process.
  3. Receiver - is the one who will know how to process the request and return back the response.
  4. Client - is the one who will creates the request, it may be one or multiple.

USECASE

Consider the use case of food ordering in a restaurant.
  1. Customer who will order the food to a Waiter.
  2. Waiter will get the order details, but don't know how to prepare the ordered food.
  3. Waiter will pass the order details to the Chef who will know how to prepare different food items.
  4. Chef will prepare the ordered foods and handover to the Waiter and he will serve (call back) to the customer.
Here
Command = FoodOrder
Invoker = Waiter
Receiver = Chef
Client = Customer
Now we will try to implement the restaurant usecase.
Let us create a Food Object.
public class Food {
 private String name;
 private int quantity;
 private int price;
  
 // getters and setters
}

Create a Command Interface with desired action defined.
public interface FoodOrder {
 Food prepareFood();
}

Create implementation for the Command.
public class IndianFoodOrder implements FoodOrder {
 public Food prepareFood() {
  // logic to prepare the indian food.
 }
}
public class ChineseFoodOrder implements FoodOrder {
 public Food prepareFood() {
  // logic to prepare the chinese food.
 }
}


Create the Invoker.
public class Waiter {
 // store all the customer food .
 private List<FoodOrder> foodOrders = new ArrayList<FoodOrder>();
  
 // store all the ordered foods for the call back to customer.
 private List<Food> orderedFoods = new ArrayList<Food>();
 // store the orders.
 public void placeFoodOrder(FoodOrder food) {
   foodOrders.add(food);
 }
 // get the prepared food.
 public List<Food> serve() {
   // logic to prepare the food.
   return orderedFoods;
 }
}

Create the Receiver.
public class Chef {
public Food preparChineseFood(String food) {
   // logic to prepare the Chinese food.
 }
 public Food prepareIndianFood(String food) {
  // logic to prepare the Indian food.
 }
}

Create the Client.
public class Customer {
 public static void main(String[] args) {
   // Call a Waiter
   Waiter waiter = new Waiter();
 
   // Order Indian Food and pass the order to a Chef
   waiter.placeFoodOrder(new IndianFoodOrder("idly", new Chef()));
 
   // Order Chinese Food and pass the order to a Chef
   waiter.placeFoodOrder(new ChineseFoodOrder("noodles", new Chef()));
   // Get the ordered foods and enjoy.
   for (Food food : waiter.serve()) {
     System.out.println("Food Name: " + food.getName()
                      + "\nQuantity: " + food.getQuantity()
                      + " plates\nPrice: "
                      + food.getPrice() + " rupees\n");
   }
 }
}

SUMMARY

  1. Command design pattern reduces the decoupling between Invoker and Receiver.
  2. Helps to achieve the callback mechanism.
  3. Command pattern will be implemented like switch off and on mechanism (undo and redo operations).

Hope this example clarifies the Command Design Pattern.
Please share your thoughts in comment box.
Happy Knowledge Sharing!!!

Friday, March 10, 2017

Functional Interface in Java 8

INTRODUCTION

Functional Interfaces meant for performing a single task. In programming way, a Functional Interface will have only one method. Some of the examples are:
  1. Runnable - has only run() method.
  2. Callable - has only call() method.
  3. Comparable - has only compareTo() method.
  4. ActionListener - has only actionPerformed() method.
Java 8 introduced lot more functional interfaces and all are packaged into java.util.function. The notable point here is that there is NO Class defined in this package.
Some of the major Functional Interfaces are:
  1. Function
  2. Predicate
  3. Consumer
  4. Supplier
In this post, we are going see how can we use those Functional Interfaces.
Java 8 also introduced a separate Annotation called @FunctionalInterface to indicate the Interface is Functional Interface. Using this annotation, we can create our own Functional Interfaces.
Let us have a Model Class: Person
public class Person {
 private String firstname;
 private String lastname;
 private Gender gender;
 private String address;
 private int age;
 private int phone;
.....
}

More details on each Functional Interface below.

FUNCTION INTERFACE

Function interface will be assigned as the result of Lambda expression or Method references.
Function<T,R> -> here T denotes the Type of the input and R denotes the Result of the output.
Consider If we want to print the firstname first followed by lastname from the list of person, we can do as below.
Create a list of the person object.
List<Person> persons = Arrays.asList(new Person[]{
  new Person("Arun", "Kumar", Gender.MALE, "Hydrabad", 55, 88000),
  new Person("Bala", "Ram", Gender.MALE, "Chennai", 23, 96000),
  new Person("Cavin", "Raj", Gender.MALE, "Bangalore", 3, 86000),
  new Person("Nancy", "David", Gender.FEMALE, "Delhi", 1, 97000) });

Function<Person, String> firstNameFirst = p -> "Name: "
+ p.getFirstname() + "," + p.getLastname()
+  "\nAddress: " + p.getAddress() + "\nPhone: " + p.getPhone();
here Type of the Input is Person Class and Result of the output is String. And go on print as below.
for (Person person : persons){
 System.out.println(person.printMe(firstNameFirst));
}

Chain operations are helpful to reduce the complexity of the code. For example, if we want to calculate multiplication of input after the sum, then we can do it easily by below example.
public static int calc(int value, Function<Integer, Integer> operation) {
return operation.apply(value);
}

Function<Integer, Integer> increment = e -> e + 1;
Function<Integer, Integer> multiplication = e -> e * 2;
System.out.println("Sum and Multi: "
+ calc(10, increment.andThen(multiplication)));
And very easy to add another into that existing chain.

Function<Integer, Integer> division = e -> e / 2;
System.out.println("Sum, Multi and Division: " +
  calc(10,increment.andThen(multiplication).andThen(division)));     

PREDICATE INTERFACE

Same as Function, Predicate also can be assigned as the result of Lambda expression or Method references.
Predicate<T> - T indicates the Type of the input. Only one input and output the result as boolean.
Consider if we want to categorize the persons based on their age, then we can apply the Predicate and group them as below.
Create an Enum for person category.

public enum PersonCategory {
 CHILDREN, TEEN, OLD;
}
Create a method which will accept the PersonCategory and result in the person who belongs to which category.

public static Predicate<Person> getCategory(PersonCategory category) {
 Map<PersonCategory, Predicate<Person>> categories
      = new HashMap<PersonCategory, Predicate<Person>>();

 Predicate<Person> children = p -> p.getAge() < 12;
 Predicate<Person> teenage = p -> p.getAge() > 12 && p.getAge() < 25;
 Predicate<Person> older = p -> p.getAge() > 25;

 categories.put(PersonCategory.CHILDREN, children);
 categories.put(PersonCategory.TEEN, teenage);
 categories.put(PersonCategory.OLD, older);

 return categories.get(category);
}
Now apply the filter using this Category and print it.

persons.stream().filter(getCategory(PersonCategory.OLD))
               .forEach(Person::firstNameFirst);

CONSUMER INTERFACE

Consumer<T> - T denotes the type of the input and it will not return any result.

List<Person> persons = Arrays.asList(new Person[] {
       new Person("A", "a", Gender.MALE, "Hydrabad", 55, 88000),
       new Person("B", "b", Gender.MALE, "Chennai", 23, 96000),
       new Person("C", "c", Gender.MALE, "Bangalore", 3, 86000),
       new Person("D", "d", Gender.FEMALE, "Delhi", 1, 97000) });
Now create a consumer with list of person with first name first.
Consumer<Person> consumer = Person::firstNameFirst;
Now using consumer object, we can add a new Person as below.
consumer.accept(new Person("E", "e", Gender.MALE, "Kerala", 33, 87874));

the main beauty of this code is, we are not at all modifying the existing person list rather we are adding a new Person dynamically.

SUPPLIER INTERFACE

Supplier<T> - T denotes the type of output by the Supplier.
Consider the below example to print the age of the person. It will accept the value but will not return anything.

public class SupplierInterface {
 public static void main(String[] args) {
   Supplier<Person> supplier = () ->
          new Person("Anand", "Kumar", Gender.MALE, "Hydrabad", 55, 88000);
   printAge(supplier);
 }
 private static void printAge(Supplier<Person> supplier) {
   System.out.println(supplier.get().getAge());
 }
}

CUSTOM FUNCTIONAL INTERFACE

We can create our own functional interfaces using @FunctionalInterface annotation.
For example, if we want to calculate Sum, multiplication, we can do it as below.

public class CustomFuncationInterfaces {
 public static void main(String[] args) {
   Sum sum = (a, b) -> a + b;
   System.out.println("Sum is: " + sum.add(2, 4));

   Multiplication mul = (x, y, z) -> x * y * z;
   System.out.println("Multiplication is: " + mul.mul(2, 3, 4));
 }
}

@FunctionalInterface
interface Sum {
 int add(int a, int b);
}

@FunctionalInterface
interface Multiplication {
 int mul(int a, int b, int c);
}
Hope this post throws some lights on Functional Interfaces in Java 8.
Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!