Monday, March 13, 2017

Mocking in Java using Mockito


Before talking about Mockito Framework. Let’s see why do we need it at the first place and how it can be helpful.

Last year, I was working on one project which talks to other third party services as well as with the database connection and to test the functionality of my application, third party application should be up and running. There can be a chance where all these services might not available during unit testing.

As you can see, your application is completely dependent on other application and what if:
  • Third party application is down
  •             You cannot connect to database to test your functionality

At such situation, mocking becomes a natural solution for unit testing. Using Mockito, you don’t really need a database connection. You just need a mock object that returns the expected result.

Mockito: Introduction


Mockito is a mocking framework, the JAVA-based library that is used for effective unit testing of JAVA applications. It lets you write beautiful tests with a clean & simple API and used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing like we don’t require a database connection or properties file read or file server read to test a functionality. A mock object returns a dummy data corresponding to some dummy input passed to it.

It facilitates creating mock objects seamlessly and uses Java Reflection in order to create mock objects for a given interface. Mock objects are nothing but the proxy for actual implementations.

Download


You can download the JAR file and place it in your project class or If you are using Maven, then you need to add its dependency in the pom.xml file, as shown below.
                        <dependency>
                                    <groupId>org.mockito</groupId>
                                    <artifactId>mockito-all</artifactId>
                                    <version 1.9.5</version>
                        </dependency>

You can add it in gradle too:

repositories { jcenter() }
dependencies { testCompile "org.mockito:mockito-core:2.+" }

Implementation:


Mockito provides various Annotation/Class/Function using which we can integrate mock object into out JUNIT test cases.

I’ve uploaded one tutorial on GITHUB which we will refer it to here to understand the behavior/implementation of Mockito framework.

In EmployeeServiceTest_Annotation Class, I am invoking employeeServiceImpl.addEmployee(employee) to add the employee object and expecting long Id after the creation of object into the database. This API internally call employeeDao object to persist the data into the database and get the results.
Over here, employeeServiceImpl is the class in which we will inject the employeeDao mock object.

Let’s start implementing it:

Mockito supports the creation of mock objects using the static mock() method or using @Mock annotation and to use this annotation, we must invoke the static method MockitoAnnotations.initMocks(this) or use @RunWith(MockitoJUnitRunner.class) to populate the annotated fields.

@InjectMocks: it is used to create and inject the mock object.
@Mock: It is used to create the mock object to be injected


Adding behavior to mock object:

Mockito provides when(… .).thenReturn(… .) method to configure which values should be returned at a method call based on specific condition. It will return a value once it matches with a condition.

Eg: when(employeeDao.addEmployee(any(Employee.class))).thenReturn(1L);

It will return 1 whenever we invoke addEmployee(…) with any Employee object.
If you specify more than one value, then it will return in the order of specification until the last one is used.

Iterator it= mock(Iterator.class);
          when(it.next()).thenReturn("A").thenReturn("B");


Verify the calls on the mock objects

Mockito provides another method called verify() which is similar to When() but does not check the result of a method but it checks that a method is called with the right parameters. 

Eg: verify call to employeeDao to make sure it get called and limit the method call to 1, no less and no more calls are allowed
            verify(employeeDao, times(1)).addEmployee(any(Employee.class));


Exception handling

Mockito provides the capability to a mock to throw exceptions so exception handling can be tested.

Eg: add the behavior to throw exception
                        doThrow(new Exception("Employee not found")).when(employeeDao).getEmployee(2);


Ordered Verification

Mockito provides Inorder class which takes care of the order of method calls that the mock is going to make in due course of its action.
Eg: Create an inOrder verifier for a single mock

                        InOrder inOrder = inOrder(employeeDao);

            // following will make sure that add is first called then subtract is called.
                        inOrder.verify(employeeDao).addEmployee(any(Employee.class));
                        inOrder.verify(employeeDao).getEmployee(1);


Spying

Mockito provides an option to create spy on real objects. When a spy is called, then the actual method of the real object is called.

Eg:  create a spy on actual object
                        employeeDao = spy(spyEmployeeDaoImpl);



Timeouts

Mockito provides a special Timeout option to test if a method is called within its stipulated time frame.

Eg: Verify call to add employee method to be completed within 100 ms
                        verify(employeeDao, timeout(100)).addEmployee(any(Employee.class));



You can download the source code from GITHUB.

Happy Coding..!!!

Wednesday, February 22, 2017

OAuth vs SSO: Which One Should I Use?

Currently, I am working on one project which provided me a lot of opportunities to learn about OAuth 2.0 and SAML and better understanding on which one to choose for SSO strategy.
I am choosing this topic because most of the people get confused between these two. While they have some similarities but they are very different too and to put it one line. I would say “OAuth is not Single Sign-On”


What is the difference between OAuth 2.0 and SSO?



OAuth (Open Authorization) is a standard for authorization of resources. It does not deal with authentication. It allows secure authorization in a simple and standard method from web, mobile and desktop applications.

If you try to log into Stack Overflow using Facebook, you’ll be redirected to Facebook’s website and will see something like the following:



Once authenticated with Facebook, it will ask for Stack Overflow’s permission to access your resources like your name, Email id, Profile picture and so on. This is an authorization request like what Stack Overflow can do and what cannot do?

SAML: Security Assertion Markup Language is an XML-based open standard data format for exchanging authentication and authorization data between parties, in particular, between an identity provider and a service provider. It is an umbrella standard that encompasses profiles, bindings and constructs to achieve Single Sign-On (SSO), Federation and Identity Management.

SSO is an authentication/authorization flow through which a user can log into multiple services using the same credentials.
For instance, at your company where we have various applications like leave application, lunch application, career application and so on and we can configure all these applications to one Active Directory for authentication. Another example can be Atlassian account where you once logged in can use their other applications like Bamboo, JIRA, Confluence and so on.

Both examples represent SSO.

One of the main benefits to using SSO is that your users have only a single account and password to remember which gets them into all of their services.


Conclusion: When Should I Use Which?


  • If your use case requires a single account to log into many applications, then go with SSO like your internal company applications.
  • If your use case involves providing access (temporarily or permanent) to resources (such as accounts, pictures, files etc.), then use OAuth.
  • If your use case requires a centralized identity source, then use SSO.
  • If your case requires to have accounts on many different services, and selectively grant access to various services, use OAuth

Friday, February 17, 2017

Set up Shibboleth SP as a SAML 2.0 service provider with G Suite

Prerequisite:

  1. Basic understanding of SAML 2.0, SSO and Shibboleth SP.  
  2. SP setup up and working on your instance.
  3. Must having administrator account to register your SP on G suite

G Suite setup:

  • Login to https://admin.google.com using your administrator account.
  • Click Security > Set up single sign-on (SSO)
  • Click the Download button to download the Google IdP metadata and the X.509 Certificate
  • Now click on Apps > SAML apps.
  • Select the Add a service/App to your domain link or click the plus (+) icon in the bottom corner. The Enable SSO for SAML Application window opens.
  • Click SET UP MY OWN CUSTOM APP
  • We have already downloaded the certificate and Idp Metadata, click NEXT
  • On the Basic application information window, Enter the Application name and Description values.
  • In the Service Provider Details section, enter the following URLs into the Entity ID, ACS URL, and Start URL Fields:
    1. ACS URLhttps://your-domain-name.com/Shibboleth.sso/SAML2/POST
    2. Entity IDyour-domain-name.com/shibboleth
    3. Start URL: https://your-domain-name.com/app
Note: You can get the ACS URL and entityID by hitting https://your-domain-name/Shibboleth.sso/Metdata. It will download the Shibboleth SP metadata file containing all the URLs like entityID in the first few lines and ACS URL which is nothing but AssertionConsumerService URL having SAML 2.0 HTTP-POST binding.
    <md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://your-domain-name.com/Shibboleth.sso/SAML2/POST" index="10"/>
  • Leave Signed Response unchecked. When the Signed Response checkbox is unchecked, only the assertion is signed. When the Signed Response checkbox is checked, the entire response is signed.
  • The default Name ID is the primary email and select EMAIL as Name ID Format.
  • Click Add NEW MAPPING and then add EMAIL and choose Basic information and Email from 2nd and 3rd drop down list.
  • Click Finish.
  • Now go to again on Apps -> SAML apps and select your APPLICATION.
  •  At the top of the gray box, click More and choose:
    1. On for everyone to turn on the service for all users (click again to confirm).
    2. Off to turn off the service for all users (click again to confirm).
    3. On for some organizations to change the setting only for some users.

Configured G Suite details in your Shibboleth SP

  • Drop the downloaded Google Idp metadata to opt\shibboleth-sp\etc\shibboleth directory.
  • Open Shibboleth2.xml file and add below snippet
    • <MetadataProvider type="XML" file="C:\opt\shibboleth-sp\etc\shibboleth\<GOOGLE_IDP_FILENAMExml>"/>    
  • Restart Shibboleth.

 Verify that SSO between G Suite and Zendesk is working

  • Close all browser windows.
  • Open https://your-domain-name.com/app and attempt to sign in.
  • You should be automatically redirected to the G Suite sign-in page or if you are having discovery page then it will come under drop down menu
  • Enter your sign-in credentials.
  • After your sign-in credentials are authenticated you're automatically redirected back to your Application.

Happy coding..!!!

Tuesday, February 14, 2017

Singleton Class Vs Singleton bean scope

I have seen people getting confused between singleton scope vs singleton design pattern. Basically, there is a bit difference between these two.

Singleton scope: The spring support five different scopes and it is used to decide which type of bean instance should be returning from Spring container back to the caller. One of the scope is Singleton and the by default scope too. It returns a single bean instance per Spring IoC container.

<bean id=”object1” class=“com.package.classname”/>

When I said, single bean instance per spring Ioc Container i.e. you will always get the same object regardless of the number of call of the same bean but if you declare another bean for the same class then you will get another object for another bean.

Let’s understand this with an example:

<bean id=”object1” class=“com.package.classname”/>
<bean id=”object2” class=“com.package.classname” scope=”prototype”/>
<bean id=”object3” class=“com.package.classname”/>

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(APP_FILE);
Classname name1 = (Classname) context.getBean(“object1”);
Classname name2 = (Classname) context.getBean(“object2”);
Classname name3 = (Classname) context.getBean(“object3”);


name1==name1 // true, object1 is singleton, calling again n again will give the same object.
name2==name2 //false, object2 is prototype, calling again n again will give the different object
name1==name3 // false, object1 & object3 is singleton but two different bean.

So, the question arise how will you achieve the Singleton design pattern in Spring?

Spring framework provides facility to inject bean using factory method i.e. that returns an instance of its own class and can be used in singleton design pattern.

public class Singleton {
         
                private static volatile Singleton instance = null;
                private Singleton(){        
                }
                                public static Singleton  getInstance(){
                                if(instance == null) {
                                                synchronized (Singleton.class) {
                                                                if(instance == null){
                                                                                instance = new Singleton();
                                                                }
                                                }
                                }
                                return instance;
                }
           }

<bean id="object4" class="com.package.Singleton" factory-method="getInstance"/>
       <bean id="object5" class="com.package.Singleton" factory-method="getInstance"/>
Singleton singleton1= (Singleton) context.getBean(“object4”);
Singleton singleton2= (Singleton) context.getBean(“object5”);

singleton1==singleton1 // true, object1 has singleton scope, calling again n again will give the same object.
singleton1==singleton2 //true, Class is a singleton and we are getting an object from getInstance using factory-method.

Conclusion: Singleton scope is a bit different from a single design pattern, Returns a single bean per Spring Ioc Container whereas singleton design pattern will always return the same object.
Singleton scope can be useful where you are creating multiple datasource in your application where each datasource point to a different object.

You can download the code source from my GitHub repository.

Happy coding!!!




Friday, January 13, 2017

How to uinstall MySQL completely from Windows OS?

I was running some script which did some changes to my database and corrupted my root permission. Tried so many things but didn't work out.

Finally, I decided to uninstall the MySQL from my instance and install a new one but again it was not an easy job as MySQL stores file at the various locations that you have to removed manually before starting from the scratch.

Simple steps to uninstall MySQL:

  1. Stop MySQL services and remove services by executing below command in command prompt (Start it as Administrator)
    1. Net stop MySQL
    2. Sc delete MySQL
  2. Uninstall MySQL program from the control panel.
  3. #2 will uninstall the program but will not remove all the files from your machine which we have to do it manually.(Removing all files will remove existing database. Take the backup, if you need it in future.)
    1. C:\Program Files\MySQL
    2. C:\Program Files (x86)\MySQL
    3. C:\ProgramData\MySQL
    4. C:\Users\<USERNAME>\AppData\Roaming\MySQL
  4. Restart your instance and install it again.
Happy coding..!!!


Friday, December 16, 2016

What is JSON Web Token?

1. Overview

JSON Web Token or JWT (jot) for short is an open standard (RFC 7519) that defines a compact, URL-safe means of representing claims to be transferred between two parties.  The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.

2. Structure

The compacted representation of a signed JWT is a string that has three parts, each separated by a dots (.) :

Eg: 
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.
eyJzdWIiOiJBYmR1bCIsImlhdCI6MTIzNDU2Nzg5MCwiZXhwIjoxMjM0NTY3ODkwLCJuYmYiOjEyMzQ1Njc4OTAsImlzcyI6Imh0dHA6Ly93YWhlZWR0ZWNoYmxvZy5pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJhZG1pbiI6dHJ1ZX0
.
Ats92uWxgSjQ8vFgQieK9tpBi66csIFHxkTke70FGlI

Each section is Base64Encoded and the first section is called header, the second section is payload and the third section is Signature.

2.1 Header

It consists of two parts: Hashing algorithm (HMAC SHA256 or RSA) and type of the token and to form the first part of the JWT, you need to do Base64Url encoded.

Eg:
{
  "alg": "HS256",
  "typ": "JWT"
}


2.2 Payload

Payload contains the Claims. JWT Claims Set represents a JSON object whose members are the claims conveyed by the JWT i.e. Data to be shared between the applications.
Eg:
{
  "sub": "Abdul",
  "iat": 1234567890,
  "exp": 1234567890,
  "nbf": 1234567890,
  "iss": "http://waheedtechblog.in",
  "scope": ["read","write"],
  "admin": true
}

There are three types of claims: reserved, public, and private claims.

2.2.1 Reserved Claims

These are standard predefined claims defined in the specification which can be used to provide a set of useful claims. Some of them are : 
a. "iss" (Issuer) Claim
b. "sub" (Subject) Claim 
c. "aud" (Audience) Claim
d. "exp" (Expiration Time) Claim
e. "nbf" (Not Before) Claim
f. "iat" (Issued At) Claim
g. "jti" (JWT ID) Claim  


2.2.2 Public Claims

These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.


2.2.3 Private Claims

  All the custom claims come under private claims and it is created to share information between parties that agree on using them.
{
"scope": ["read","write"],
 "admin": true
}

2.3 Signature

To create the signature part, you have to take the encoded header, the encoded payload, and a SECRET_KEY, the algorithm specified in the header, and sign that.
Eg:
if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)
The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.

You will get the below JWT token if you combine above header and payload and will use secret as SECRET_KEY.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJBYmR1bCIsImlhdCI6MTIzNDU2Nzg5MCwiZXhwIjoxMjM0NTY3ODkwLCJuYmYiOjEyMzQ1Njc4OTAsImlzcyI6Imh0dHA6Ly93YWhlZWR0ZWNoYmxvZy5pbiIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJhZG1pbiI6dHJ1ZX0.Ats92uWxgSjQ8vFgQieK9tpBi66csIFHxkTke70FGlI


3. How do JSON Web Tokens work?


1. Browser will log in to Authorization Server via username/password

2. Authorization Server will authenticate the user and will create the JWT token signed by its key and will return in the response.
3. Now, Browser will access the Application Server by JWT token as Authorization bearer <token> in the header.
4. Application Server will verify JWT using secret key (In such scenario, Key must be shared between Authorization Server and Application Server), Decode the String, verify the claims and will return the response.


4. Open Source libraries:

There are already open source libraries available in the market using which you can create and verify the access token. 
Source code for implementation of above library can be downloaded from GITHUB

5. Conclusion:

We went over what JWT are, how they are created and validated, and how they can be used to ensure trust between an application and its users. This is a starting point for understanding the fundamentals of JWT and why they are useful. 

6. References:



Friday, December 2, 2016

@Embeddable and @Embedded in Hibernate Annotation

Before jumping to @Embeddable and @Embedded annotation. Let me explain about hibernate different objects:
        Entity Object
o   Entity object are those object which can stand alone like Student or Professor and has its own database identity.
        Value Object
o   Objects which cannot stand alone like Address as you need to map address with some Entities like Student. It will belongs to an entity, and its persistent state is embedded in the table row of the owning entity

In short, always use @Embeddable for the value object and @Embedded with the entity class.

Let's understand it by a simple example:

We have one Address (Value object) and it is having attributes like city, state, zip code. Now we have two more different entity Student and Professor (Entity Object). Student or Professor can have Address attributes just by embedding the Address into its Entity.

The @Embedded annotation is used to specify the Address entity should be stored in the STUDENT table as a component.

@Embeddable annotation is used to specify the Address class will be used as a component. The Address class cannot have a primary key of its own, it uses the enclosing class primary key.



Download the source code of this example from Github.

You will see the output once you execute the Application class from source code


and will create the following tables in the database



Happy Coding..!!!

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...