Friday, 29 June 2018

Part 1 - REST API Best practices and implementing them with Spring Boot

This article describes the best practices of implementing REST API.

Before we jump into the actual implementation, lets first understand the design principles involved in API design.


API Design principles

  1. Present APIs as products
    • APIs are not integration services that happen to use HTTP and JSON
    • They are business products that must be managed as a complete product offering
    • And although created and managed by different teams they should have a similar look and feel
  2. Design APIs with the consumer in mind
    • Develop APIs as though you consumers are your customers
    • APIs should be more developer-friendly and Easy to Consume
    • Simple to Expose to external third-parties in future
    • Don't leak internal context to the consumer
    • Make APIs easy to learn, hard to misuse, audience-oriented
  3. Prefer REST-based services over SOAP

REST API Design principles

  1. Use RESTful URIs and actions
    • /policies - refers to a policy resource collection
    • /policies/7895544 - refers to a policy resource collection
  2. Use HTTP verbs to act on you resources
    • Resources should be acted on using HTTP methods GET, PUT, POST, PATCH, DELETE for example GET /policies/789554
    • HTTP methods should perform predictable actions on the resource. For example, don't use POST to retrieve a resource, and don't use DELETE to create a resource.
  3. Nouns are good, verbs are bad
    • Resources must use plural nouns, such as accounts and not account
    • Do not use verbs in URI, /getaccount or createcar
    • The method exposing the webservice should be verb not the associated URI
  4. Use sub-resources to represent relationships
    • For e.g if a Department has many Employees and you need to get the list of employees in a department, the URI should be 
      GET /departments/  - Get all Departments
      POST /departments/  - Create a Department
      GET /departments/1234  - Get a Department
      GET /departments/1234/employees - Get all Employees in a Department
      POST /departments/1234/employees - Create an Employees in a Department
      GET /departments/1234/employees/2 - Get a Employee in a Department

  5. Version your API
    • All APIs should be versiones
    • Use only a major version number prefixed with a "v", eg /v1
  6. HATEOUS compliant
    • The API should be HATEOUS compliant. All future actions the client may take are discovered within resource representations returned from the server. The media types used for these representations, and the link relations they may contain, are standardized.
    • For e.g for a GET /departments/
    • {
      "id" : 1,
      "name" : "Head Office",
      "Address" : "In a far galazy",
      "links" : [
         {
             "rel" : "self",
             "href" : "http//abc.com/api/v1/departments/"
         },
         {
             "rel" : "find",
             "href" : "http//abc.com/api/v1/departments/{id}",
             "type" : "GET"
         },
         {
             "rel" : "delete",
             "href" : "http//abc.com/api/v1/departments/{id}",
             "type" : "DELETE"
         }
         
      }
    • As seen above the response has a link to self and also other possible resources the client can use

  7. API must be secured
    • APIs must be secured and there are no exceptions
    • OAuth2.0 can be used for securing APIs.
    • Choose the best grant type e.g authorization code/password/client credential
  8. Error Handling
    1. Use descriptive error messages and status code
    2. For e.g if the request is to find a employee and the employee id provided is not correct, return a 404 Resource Not Found status code and not a 200 OK
    3. Trap all errors and always return a valid JSON response

    4. {
          "timestamp": "2018-06-27T12:42:39.238+0000",
          "status": 400,
          "error": "Bad Request",
          "message": "Do not send ‘id’ as part of request",
          "path": "/spring-security-oauth-resource/rest/v1/employees"
      }
      
      

      Another example for multiple errors would be like below:
      {
          "status": 405,
          "timestamp": "02-07-2018 03:16:55",
          "path": "/spring-security-oauth-resource/rest/v1/departments",
          "message": "Validation failed for object='department'. Error count: 3",
          "sub_errors": [
              {
                  "field": "name",
                  "message": "name cannot be Blank"
              },
              {
                  "field": "id",
                  "rejectedValue": 1111,
                  "message": "must be null"
              },
              {
                  "field": "knownName",
                  "message": "known_name cannot be Blank"
              }
          ]
      }
      
  9. Things to avoid
    • Dont use querystring argumets to retrieve by primary key:
    • For eg : dont use /policies/?policy_number=32323
      Rather Use /policies/12333
    • Dont use mixed-case in URLs:
    • For eg : dont use /Policies/32323
      Rather Use /policies/12333

Thursday, 11 January 2018

Friday, 22 December 2017

Java Blockchain Mining and Consensuses

Mining and Consensuses in Blockchain


In the previous blog we got to know what a Blockchain is, and how you can we create a Java based Blockchain which can not be tampered (Integrity).

Blockchain has couple of more design principles other than Integrity : Decentralized, Consensuses, Public Ledger etc. Before we jump to Mining it is important to understand these concepts first.

Public Ledger 


Assume that different participants are adding transactions and blocks to a Blockchain. That means there has to be a central Blockchain that is accessible to all, since all participants needs to add block to the existing Blockchain, This means there has to be a master participants governing and storing the Blockchain. But this is against the principle of Blockchain (Decentralized). There is no master participant in the network. To solve the above issue, each participant keeps a copy of the Blockchain with itself. Once a block is added, it is distributed across the network and all participants update their Blockchain. This concept is called Public Ledger. A ledger (list of transactions) which is public.

But this causes another problem in the network.


Lets assume that 2 participants are trying to add a block, simultaneously to a Blockchain.  Only one can be allowed to do so and the other has to be discarded since the previous hash in that block will be invalid.


Java Blockchain tutorial

This blog provides a working Blockchain example in Java.

Before we jump into the actual code, lets first understand the basics of Blockchain.

Introduction :


Lately, you might have herd a lot of buzz around different crypto-currencies emerging in market : Bitcoin, Etherium, Ripple, Dash ... and the list goes on. The market share of Bitcoin has gone exponentially up from $ 4000 to $ 17000 in just three months. Other currencies are also following the same trend.



The reason that these currencies are getting so much traction is the common architecture design they share : Blockchain

Bitcoin is not Blockchain and Blockchain is not Bitcoin. Bitcoin is just one implementation of crypto-currency use case that can be build on Blockchain.


Tuesday, 10 May 2016

Java Annotations

Annotations were a feature introduces in Java 5. By the way the current version of java is 8.

Annotations tell the compiler about additional information.

Annotations commonly used are :

@Entity
@RequestMapping



Annotations can be applied to class, method, method parameter and instance variable

Monday, 18 April 2016

Exception Handling Objective Question and Answers

The below blog has objective questions on Exception Handling. It concentrates on usage of keywords like throws, throw, try/catch and Exception

This blog is a extension to previous blog of Core Java Objective Question Test 1


1.
1. public class Test {
2.  public static void main(String[] args) {
3.   System.out.println("hi");
4.   try {
5.    System.out.println("Here");
6.    int j=1/0;
7.    throw new UserNotFoundException();
8.    
9.   } catch (UserNotFoundException e) {
10.    System.out.println("Caught");
11.    e.printStackTrace();
12.   } finally{
13.    System.out.println("in finally");
14.   }
15.   System.out.println("After catch");
16.  }
17.  }


Wednesday, 13 April 2016

JAVA and OOPS multiple choice questions part 2

2.
package inter;

public interface Shape {

}

package inter;

public class TestInter {
 public static void main(String[] args) {

  Shape shape = new Shape();
 }
}
Output
1. Compilation Error. Object of interface cannot be created.
2. No error


3.
package inter;

public interface Shape {

 public int area;
}

package inter;

public class TestInter {
 public static void main(String[] args) {

  System.out.println(Shape.area);
 }
}

Output
1. Compilation Error. Class variable in interface should be initialized.
2. Compilation Error. Class variable in interface should be static.
3. No error


4.
package inter;

public interface Shape {

 public int area=100;
}

package inter;

public class TestInter {
 public static void main(String[] args) {

  System.out.println(Shape.area);
 }
}

1. No Error
2. Compilation error : Class variables should be static and final


5.
package inter;

public interface Shape {

 public double pie=3.14;
 
 double getArea();
}

package inter;

public class Circle implements Shape {

 double radius;
 
 public Circle(double radius){
  this.radius=radius;
 }
 
 public double getArea() {
  
  return pie * (radius*radius);
 }

}

1. Compilation Error. getArea() in Interface Shape should be public and abstract.
2. No error



6.
package Collections;

import java.util.List;

public class TestCollection {

 public static void main(String[] args) {
  
  List l = new List();
 }
}


1. Compilation Error. List is an Interface. You cannot instantiate an interface.
2. No Error



7.
package Collections;


public class TestCollection {
 
 int instanceVariable;
 
 public int doSomething(){
 
  System.out.println(instanceVariable);
  int localVariable;
  return instanceVariable+localVariable;
 }

 public static void main(String[] args) {
  
  TestCollection testCollection  = new TestCollection();
  testCollection.doSomething();
  
 }
}


1. 0
2. Compilation Error: localvariable not initialized.




8.
package annot;

class Animal{
 public void eat(){
  System.out.println("Call Aniaml");
 }
}

public class TestClass {
 public static void main(String[] args) {
  callEat(new Animal(){
   public void eat(){
    System.out.println("Call Aniaml of Test");
   }
   public void talk(){
    System.out.println("Calling talk");
   }
  });
 }

 private static void callEat(Animal a) {
  a.talk();
 }
}
Options:
1. Calling talk
2. Compilation error while calling a.talk()
3. Compilation error while calling callEat() method


9.
package annot;

interface Animal{
 public void eat();
}
public class TestClass {

 public static void main(String[] args) {
  callEat(new Animal(){
   public void eat(){
    System.out.println("Call Aniaml of Test");
   }
   public void talk(){
    System.out.println("Calling talk");
   }
  });
 }
 
 private static void callEat(Animal a) {
  a.eat();
 }
}
1. Cannot instantiate an interface
2. Call Animal of Test

JAVA and OOPS multiple choice questions Test with answeres

Since now a days the number of candidates appearing for a job has increased, companies have started keeping screening process. This screening process consist of objective questions which can be answered online. Only those candidates which score good marks in Objective questions are called for personal interviews.

This blog has multiple choice OOPS and Java  questions. It is a mix of topics like Inheritance, overriding, static, constructor etc.

Read the question and try to solve it yourself. Then you can click on the Answer button to verify your answer.


Core Java Test 1 >> Core Java Test 2 >> Exception Handling Test 3


Monday, 29 February 2016

Java Access Specifier

Java has four access specifies:
1.    Public
2.    Private
3.    Protected
4.    Default

Class

A class can be defined either as public or default. Note: default is not a keyword as public. When no access specifier is mentioned default access specifier is applied.

Friday, 8 January 2016

jQuery Calendar Plugin with events



Features:
1. Customize to Events, Icons and different background colours with CSS.
2. Ajax support.
3. Events available on click of day and events.
4. Responsive

Thursday, 10 December 2015

Java Interview Questions for 2 to 5 yrs - Java Developer

Hello All,
This blog lists the interview questions that you are likely to face in an Interview if you are Java developer between 2 to 5 years.
When you reach experience level of more than 2 years it is assumed by the interviewer that you have good hand on experience in Java stack.
Sometimes the interviews are for a specific project. Like a project may require candidate to have experience in Spring or Struts or Hibernate. Or sometimes the interview is not for a specific project and is for a open requirement.
Sometimes specific skills are looked for, like the candidate should have experience in SOAP and REST Web-services.

The interviewer is not expecting the candidate to know the designing or high level architecture of the project. What he is expecting is the candidate should be aware of the Project, the technologies used and should be aware of the role he played in the project. As this is not a fresher interview the questions would start with basics and then go in deep.

Below here are the list of questions.

How to create a Software application

There has been lot of discussion on how a Software application should be developd.

What should be the Architecture?
What can be the best framework?
What should be the design?
What design principles can be applied?
How to cater to always changing requirements?
How to for-see a requirement?
Which database to use?


Thursday, 19 November 2015

Different types of Computer Viruses

                                              Different types of Computer Viruses

A computer virus is often defined as a program which specifically designed in order to cause harm to the computer. Computer viruses are transmitted and affect the computer via portable devices, files that are being downloaded using the internet, malicious scripts and many more. A virus gets associated with the host file and infects the computer, each and every time the user clicks on the particular infected file. Few viruses can replicate themselves and can actually cause further harmful damages to the computer. Here is a list of different types of Computer Viruses and what do they do.

Macro Viruses
Macro Viruses generally affect files that were created by using certain applications and programs which contain macro files, for example pps, xls, doc and mdb. These macro files automatically get infected along with the templates and documents associated with the files. These viruses tend to hide in documents those that are shared via e-mails and other networks. Relax, bablas, Melissa.A and 097M/Y2K Aare name of Macro Viruses that can affect files and documents stored in a computer, quite harmfully.

Saturday, 5 September 2015

Java Developer 4 to 6 yrs exp Interview at Cognizant

Following were the questions which are asked to my colleagues at experience of 4 to 6 years.

  1.  Tell me about your current project ?
  2.  What were your roles and responsibilities in your project?
  3.  Can you draw architecture diagram of your project?

Monday, 17 August 2015

Java 8 New Features

Java 8 comes with very exciting features of functional programming with lambda expression and streams.

Lets take a look at it features

Lambda Looping

Lambda expression can be used for looping over a Collection.

Friday, 3 July 2015

Custom Java HashMap - Internal Working

HashMap is a Collection class in Java that stores objects with the help of hascode and equals. It is said to be faster in retrieving objects.
Lets create a custom implementation of HashMap  and understand how it works. To understand HashMap you need to first understand Singly and DoublyLinkedList.

HashMap stores objects in form of Key and Value. A value can be fetched by passing the Key.

HashMap stores objects into different buckets(LinkedList). The object with same hashcode are stored in same LinkedList. Remember that the objects are stored in key-value pairs. The hashcode of key is used and not the hashcode of value. Only Key alone is required to put and get the object. Value is just a object placed against the key, So depending upon how many objects(Keys) are present with different hashcodes, that many LinkedList gets created.

Tuesday, 2 June 2015

Symmetric Key Encryption between JAVA and IOS

There has been a exponential increase in REST services implementation between IOS/Android devices and Java Middleware, This has become the solution architecture for most applications which provide support on IOS/Android devices and also provide interface on web using java web application.



To make the communication secure it is necessary that this REST messages are made secure. This can be achieved using symmetric encryption mechanism.


Node JS Express Mongo

This blog will help you to create a NodeJS application with the help of express, jade and mongo DB


1. Install Node JS
Go to link http://nodejs.org/ and click the Install button. It will identify your workstations operating system and start download an msi file.
After the file is downloaded install it at you preferred location.


Monday, 1 June 2015

Java Singleton Pattern

Singleton pattern is the most common types of patterns used in Java. It is also very common that interviewers ask questions to explain and implement singleton pattern

Lets first define Singleton
Singleton is a class whose only one object can be created.
There are couple of ways to implement Singleton class. Lets see the simplest one first.

Share the post