Tuesday, January 22, 2019

Functional Interface and Lambda Expression




Functional Interface and Lambda Expression



Functional Interfaces

A functional interface is an interface that contains only one abstract method. It can have one or more default or static method but abstract method should be only one.

Runnable, Callable, ActionListener, Comparable are some of the examples of functional interfaces as it contains only one abstract method.

Let’s see some functional Interface implementation example:
Example 1:

public interface SimpleInterface {
    public void abstractMethod();
}
It’s a functional Interface as it only contains a single abstract method.

Example 2:
public interface ComplexInterface {
    public void abstractMethod();
    public default void defaultMethod(){
        System.out.println(“Default method”);
    }
    public static void staticMethod(){
        System.out.println(“Static method”);
    }
}
Above example #2 is also a valid functional interface as it only contains one abstract method and rest are either default or static method.

Example 3:
public interface ComplexInterface {
    public void abstractMethod();
    public void anotherAbstractMethod();
    public default void defaultMethod(){
        System.out.println(“Default method”);
    }
    public static void staticMethod(){
        System.out.println(“Static method”);
    }
}
The above example #3 is not a valid functional Interface as it contains more than one abstract method.

#1 and #2 are valid Functional Interface but #3 is not. For lambda expression, An interface must be a functional interface else you will end up in error. So, How can we force compiler to check whether the Interface is functional or not and if not then it should give compiler time error?

@FunctionalInterface Annotation
It is used to ensure that the functional interface can’t have more than one abstract method. If you add more or less abstract method then compiler will show compile time error message.

Note: An interface with one abstract method will be called as Functional Interface whether you add the @FunctionalInterface annotation or not but it is always a good practise to add annotation as it will avoid addition of extra method accidentally.

Lambda Expression

Lambda expressions is used to represent the instance of a functional interface i.e. using Functional Interface reference we are allowed to call lambda expression implementation.
If you don’t know what is lambda expression or how to write lambda expression then you can read my blog on lambda expression over here.

Let’s try to understand the above definition with few examples:


Example 4:
I am just using the example#1 over here

public interface SimpleInterface {
    public void abstractMethod();
}

Before Java 8, Either we had to create anonymous inner class or we had to implements interface to implement the function method.

class BulkyClass implements SimpleInterface {
    @Override
    public void abstractMethod(){
        System.out.println(“Abstract Method Implementation”);
    }
}

To invoke method:
class Test {
    public static void main(String[] args){
        SimpleInterface si = new BulkyClass();
        si. AbstractMethod(); // Will display message on Console.
    }
}

Now, let’s see how Functional interface can be implemented by a Lambda Expression.

Over here, We don’t need any more BulkyClasses. We can just directly call it
class Java8 {
    public static void main(String[] args){
        SimpleInterface si = () -> System.out.println(“Abstract Method             Implementation”);
        si.abstractMethod(); // Will display message on Console.
    }
}

If you observed it carefully, We’ve invoked the lambda expression implementation using Functional Interface.
Let’s see another famous Functional Interface i.e. Runnable Interface. Runnable interface contain only one method which is run and the return type is void
Similarly, We can write anonymous Runnable using Lambda
Expression.

public ThreadExampleWithJava8 {
    p.s.v.m() {
        Runnable r = () -> {//stattement1
            statement2;
        }
        Thread th = new thread(r);
        th.start();
    }
}
  • As Runnable is a functional interface, that’s why we can use lambda expression to create it’s instance.
  • Since run() method takes no argument, our lambda expression also have no argument.
  • Just like if-else blocks, we can avoid curly braces ({}) since we have a single statement in the method body. For multiple statements, we would have to use curly braces like any other methods.

Why do we need Lambda Expression

  1. Reduced Lines of Code

  2. Sequential and Parallel Execution Support

  3. Passing Behaviours into methods

Will explain the above point with example in my next blog. Over here, Let’s just focus on Functional Interface and example.

Example 5:

@FunctionalInterface
public interface firstInterface {
     public void method1();
}
@FunctionalInterface
public interface secondInterface extends firstInterface{
}
if an interface extends functional Inference and child interface does not contains any abstract method then child interfaces will also be a valid functional interface.

Example 6:
@FunctionalInterface
public interface firstInterface {
    public void method1();
}
@FunctionalInterface
public interface secondInterface extends firstInterface{
    public void method1();
}
If base and super interface contains one abstract method and both method are same then secondInterface will also be a valid Functional Interface. Why? Because of Overriding property., second Interface will have only one abstract method.

Example 7:
@FunctionalInterface
public interface firstInterface {
    public void method1();
}
@FunctionalInterface
public interface secondInterface extends firstInterface{
    public void method2();
}
Over here, Second Interface will throw compile time error as it will be having two method i.e. method2 as will as method1 from firstInterface.

Example 8:

@FunctionalInterface
public interface firstInterface {
    public void method1();
}
public interface secondInterface extends firstInterface{
    public void method2();
}

Over here, Though Second Interface is not a Functional Interface still it will not throw any compile time error as it doesn’t have @FunctionalInterface annotation.

Saturday, January 5, 2019

How to write Lambda Expression in Java 8


   How to write Lambda Expression?



With the introduction of Lambda Expression in JAVA 8, We can write more readable, maintainable and concise code but I have seen people keep forgetting the syntax of lambda expression or they are always confused with it.

In this blog, I ll just try to explain the basic things i.e. how easy is it to write Lambda Expression but before starting with the syntax, Let’ see what is lambda Expression?

In simple term, Lambda expression (->) is an anonymous function which
    - doesn’t have any name
    - doesn’t have any modifiers
    - doesn’t have any return type.

To understand it in a more easy way, Let’s first write a simple Java function which display some message on the console.

Example 1: Display Message

  1. public void display (){ 
  2.     system.out.println(“Learning Lambda Expression”); 
Now to convert the above code into lambda expression, read the lambda definition once again i.e. it says no modifiers, no return type and no function name.

Step 1: Delete public (Modifier) void (return type) and display ( function name) from first line.

  1. public void display (){ 
  2. system.out.println(“Learning Lambda Expression”); 

Step 2: Add Lambda Expression Symbol before curly braces.

           () -> {system.out.println(“Learning Lambda Expression”);}

That’s it, We have converted the normal Java code into Lambda Expression form. Just delete the name, return type, modifier and add lambda expression symbol and you are done :)


Code Optimization: The above syntax is correct but we can optimize it further...

Rule 1: if the function body has only statement then we can remove the curly braces.

             () -> system.out.println(“Learning Lambda Expression”);


Example 2: Addition of two numbers

  1. public void sum(int x, int y) { 
  2.     system.out.println(x+y); 
The lambda expression for #2 after removing modifier, name, return type and after applying Rule#1 will be

             (int x, int y) -> system.out.println(x+y);

Isn’t it simple? Right?

Let's see the second rule


Rule 2: Use Parameter type Inference. If you don’t know what is Type Inference then you can read my blog over here. In one line, Type Inference is the ability of the compiler to look at the method and to guess the correct method invocation. So we can remove int type from method parameters.

           (x, y) -> system.out.println(x+y); 


Example 3: Returns the length of String

  1. public int getLength(String s){ 
  2.     return s.length(); 
The lambda expression for #3 after removing modifier, name, return type and after applying Rule#1 & Rule#2 will be

           (s) -> return s.length();

Rule 3: Again as per Type Inference, We can also ignore the return type over here as compiler can guess easily the return type.

             (s) -> s.length();

Rule 4: if the function has single parameter then we can ignore it. So the final optimize and concise Lambda expression for Example 3 would be

               s -> s.length();

That's it  for now. Will try to cover other topics of JAVA 8 in my next blog.

Happy Coding...!!!

Java 8 - Type Inference


Java 8 – Type Inference

Type inference was first introduced in JDK 7 and later improved in JDK 8. It is a feature of Java which provides ability to compiler to look at each method invocation and corresponding declaration to determine the type of argument(s).

The inference algorithm checks the types of the arguments and,if available, assigned type is returned. It tries to find a specific type which can full fill all type parameters.

Till Java 6, We have to declare an Arraylist by mentioning its type explicitly at both side.
            List<Integer> numbers = new ArrayList<Integer>();
and if we keep the type as blank at right side then Compiler generates unchecked conversion.
            List<Integer> numbers = new ArrayList<>();

With JDK 7, It got improved and we started mentioning the type of arraylist only at one side. Below we can left second side as blank diamond and compiler will infer type of it by type of reference variable. Now, compiler will not generate any warning
            List<Integer> numbers = new ArrayList<>();

Improved Type Inference in JDK 8
Now, we can call specialized method without explicitly mentioning of type of arguments.
            sum(new ArrayList<>());

Let’s see the java implementation




Wednesday, September 26, 2018

Introduction to RESTful API Modeling Language (RAML)



Introduction to RESTful API Modeling Language (RAML)

1. Overview

RAML is a YAML based language which is built on YAML1.2 and JSON for describing RESTful APIs. It provides all the information necessary to describe Restful API.
It focuses on cleanly describing resources, methods, parameters, responses, media types, and other HTTP constructs that form the basis for modern APIs that obey many, though perhaps not all, Restful constraints.

2. Requirement

Before jumping to RAML. Let’s assume we have to create one web application which is exposing CRUD Operations and couple of query parameters to access USER resources:
· POST /api/v1/users
· GET /api/v1/users
· GET /api/v1/users?username={username}
· GET /api/v1/users/{userId}
· PUT /api/v1/users/userId{}
· DELETE /api/v1/users/{userId}
All the API’s are secured via Basic Authentication and all the communication will be done over HTTPS and all the request response will be in JSON format.

3. Implementation


3.1 Adding Root level details

To start with RAML, first create a file with extension .raml and at rool level, you need to define the setting starting with RAML version.
1. #%RAML 1.0
2. title: REST Services API using Data Types
3. version: v1
4. protocols: [ HTTPS ]
5. baseUri: http://hostname/api/{version}
6. mediaType: application/json

#1 defines the RAML version
#2 Title of the application
#3 API versions
#4 HTTP or HTTPS channel
#5 URL of the application where ‘versions’ refers to a property which will be replaced with #3 version.
#6 Media type for the request/response.

3.2 Add Security

Security should also be added at the root level and as I mentioned earlier all the API’s are secured via Basic Authentication.

  1. securitySchemes:
  2. basicAuth:
  3. description: Basic Authnetication to authenticate API
  4. type: Basic Authentication
  5. describedBy:
  6. headers:
  7. Authorization:
  8. description: Used to send the Base64-encoded "username:password" credentials
  9. type: string
  10. example: Authorization NTA5NjUsInN1YiI6IkJhcmNsYXlzX1BheW1lbnRfU2Vydmlj
  11. responses:
  12. 401:
  13. description: |
  14. Unauthorized. Username/password is invalid


3.3 Add Data type

Once you are done with security then starts adding all your data type. In my case I will define it for users.
There are multiples ways to define your type:
1. You can create a new file users .raml and include the path over here (Will discuss at the end of this document).
2. Define the types after root setting using expanded syntax
3. Or you can do it via shortcut.

  1. types:
  2. Users:
  3. type: object
  4. properties:
  5. id:
  6. required: true
  7. type: integer
  8. username:
  9. required: true
  10. type: string
  11. roles:
  12. required: false
  13. type: string

Now we will see how we can define the user using shorthand.
1. types:
2. Users:
3. properties:
4. id: integer
5. username: string
6. roles?: string

? -> Adding to any property declares that the field is not mandatory.

3.4 Define Resource, method, URL parameters and query parameters


To define a resources
/users:
To add the method
/users:
get:
post:

To add the URL parameters
/users:
get:
post:
/{userId}:
get:
put:
delete:

To add the Query Parameters:
/users:
get:
description: List all users with/without filters
queryParameters:
name?: string
roles?: string
post:
/{userId}:
get:
put:
delete:

Over here, we have seen how we can declare the resources with VERB and how we can define path as well as query parameters.

3.5 Request and Response Body

In above example we have defined the users resources with POST method but have not defined the payload. Let’s see how we can add payload, response and Status Code to an API.
/users:
get:
description: List all users with/without filters
queryParameters:
name?: string
roles?: string
post:
description: create a new user
body:
application/json:
type: Users
example: { "id" : 101, "name" : "Abdul Waheed”, “roles”:”Admin” }
responses:
201:
body:
application/json:
type: Users
example: { "id" : 101, "name" : "Abdul Waheed”, “roles”:”Admin” }
500:
   body:
     application/json:
        type: Error
       example: { "message" : "Internal Server Error, "code" : 500 }

/{userId}:
get:
put:
delete:


In this example, We are performing POST operation where we are passing Users object in the form of JSON and in response we are getting STATUS code as 201 and again response type in the form of JSON.


4. Usage of Includes in RAML
In the above example, we just took one resouces but let’s assume you have to create RAML for your application where you have many resouces and each resouces have multiple consuming API.
Handling such requirement makes our .raml file more verbose and repetetive.
Using !include, we can externalize our duplicate lengthy code.
Eg: we can put the data type for a Users object in the file types/Users.raml and the type for an Error object in types/Error.raml. Then our types section would look like this:
types:
Users: !include types/Users.raml
 Error: !include types/Error.raml


5. Completing the API
After externalizing all of the data types and examples to their files, we can refactor our API using the include facility
  1. #%RAML 1.0
  2. title: REST Services API using Data Types
  3. version: v1
  4. protocols: [ HTTPS ]
  5. baseUri: http://hostname/api/{version}
  6. mediaType: application/json
  7. securitySchemes:
  8. basicAuth:
  9. description: Basic Authnetication to authenticate API
  10. type: Basic Authentication
  11. describedBy:
  12. headers:
  13. Authorization:
  14. description: Used to send the Base64-encoded "username:password" credentials
  15. type: string
  16. example: Authorization NTA5NjUsInN1YiI6IkJhcmNsYXlzX1BheW1lbnRfU2Vydmlj
  17. responses:
  18. 401:
  19. description: |
  20. Unauthorized. Username/password is invalid
  21. types:
  22. Users:
  23. type: object
  24. properties:
  25. id:
  26. required: true
  27. type: integer
  28. username:
  29. required: true
  30. type: string
  31. roles:
  32. required: false
    type: string
  33. /users:
  34. get:
  35. description: List all users with/without filters
  36. queryParameters:
  37. name?: string
  38. roles?: string
  39. response:
  40. 200:
  41. body:
  42. application:json
  43. type: Users[]
  44. example: [
  45. {“id”:1,”username”:”Abdul”}
  46. {“id”:2, “username”:”Waheed”}]
  47. post:
  48. description: create a new user
  49. body:
  50. application/json:
  51. type: Users
  52. example: { "id" : 101, "name" : "Abdul Waheed”, “roles”:”Admin” }
  53. responses:
  54. 201:
  55. body:
  56. application/json:
  57. type: Users
  58. example: { "id" : 101, "name" : "Abdul Waheed”, “roles”:”Admin” }
  59. 500:
  60.    body:
  61.      application/json:
  62.         type: Error
  63.        example: { "message" : "Internal Server Error, "code" : 500 }
  64. /{userId}:
  65. get:
  66. put:
  67. delete:

In my next blog, I ll talk about different RAML tools and the difference between SWAGGER (recently renamed to OAS) Vs RAML and which one to prefer.

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...