Wednesday, April 4, 2018

Angular Switch Statement

The ngSwitch directive is an inbuilt directive that lets you hide/show HTML elements depending on an expression.
NgSwitch uses ngSwitchCase keyword to define a set of possible element which will be selected based on the ngSwitchCase

<element ngSwitch="expression">
  <element *ngSwitchCase="value"></element>
  <element *ngSwitchCase="value"></element>
  <element *ngSwitchCase="value"></element>

For Example say we want to design a simple Component which renders different kind of Input fields like Text, TextArea etc based on the parameters we are sending. Then we need some kind of If/Else or Switch statements to select the case.
Following Plunker demonstrates working example of a ngWitchCase statement.

Here is the link to the Plunker to try it out.

Working with Base64 Decoded Image in Angular

We can save images in base64 encoded format in database. It has it's own advantages and disadvantages. But while loading those images in Angular Application, based on different factors like Content Security Policy etc, Angular does not allow to load base64 encoded images in the HTML. It will append unsafe to the url, as a result the HTML does not show the image properly.

For instance if I want to show the following image which is in base64.


I will have something similar in the HTML

<p><img src="data:image/jpeg;base64,/aaaiskk....></p>
But due to Content Security policy Angular will not load the above URL. And if you see the source then you will see that unsafe is appended before the base64 URL.

One way to workout in Angular is to Sanitize the URL so that Angular can load the URL. For that we can import DomSantitizer from @angular/platform-browser.

//Angular Controller
import {DomSanitizer} from '@angular/platform-browser';
export class Base64ImageComponent implements OnInit{
  constructor(private sanitizer: DomSanitizer) { }
  sanitize(url: string) {
    //return url;
    return this.sanitizer.bypassSecurityTrustUrl(url);
//Template HTML
<img [src]="sanitize(filePreview)"/>

A example plunker with full code can be found here

Tuesday, March 13, 2018

Rest API Design Reference

REST stands for Representational State Transfer. It is an architectural style for developing software.

Architectural Constraints

REST defines 6 architectural constraints which make any web service – a true RESTful API.
Uniform interface
Layered system
Code on demand

Uniform interface
Uniform interface suggests that the resource in a system to have only one logical URI and 
Then provide additional information to retrieve the related data. For instance we can provide
Links for related resources like child objects, parent objects etc.
User of one API end point should be able to identify and work similarly with other Resources.
Also, the resource representations across system should follow certain guidelines
such as naming conventions, link formats or data format, filter formats pagination formats etc.
All resources should be accessible in similar way and should use similar status codes.

Server should not depend on previous client state to serve next request.
Each request should be independent
of any state set in the server by previous requests.
If we replace the server with a different server serving same API’s then the Client should be work.
This is only possible if the API’s are consistent and follows same standard for all endpoints.
This way we can use load balancer to switch the server serving the API.

For the API’s to work properly it should not be assumed that server is not storing
any kind of data which might be essential for subsequent API calls.
The API should be stateless and Client should be responsible for managing the state of the application.
Client should be sending all the necessary information.

In REST, caching shall be applied on resources when applicable and then these resources MUST
declare themselves cacheable.Caching can be implemented on server or client side.
Well-managed caching partially or completely eliminates some client–server interactions unless the resouce
was changed between the last time it was requested.

Layered system
REST allow you to use a layered system architecture where you deploy the APIs on a Server A,
have intermediate systems between. Client facing urls and the actual Service.
For instance we can have a API gateway which control access to the API.
Or we can also think of load balancing architecture where the serving accepting request
actually redirect the request to a particular node.

Code on demand (optional)
Well, this constraint is optional. Most of the time you will be sending the static representations
of resources in form of XML or JSON.
But when you need to, you are free to return executable code to support a part of your application
e.g. clients may call your API to get a UI widget rendering code. It is permitted.
All above constraints helps you build a true RESTful API and you should follow them.
Still, at times you may find yourself violating one or two constraints.
Do not worry, you are still making a RESTful API – but not “truly RESTful”.

Following are the Best Practices for Designing and Developing REST

REST Resource Naming Best Practices

Use nouns to represent resources not verbs.
To describe names use concrete names (Nouns) rather then verbs.
RESTful URI should refer to a resource that is a thing (noun)
instead of referring to an action (verb) because nouns have properties as verbs do not
similarly resources have attributes. 

GET /questions
GET /questions/1

Rather then  
GET /retrieveQuestions
GET /getQuestionWithID/1

URI Case

Use lowercase letters in URIs.  According to RFC3986, URLs are “case sensitive” (except for the scheme and the host). 
When convenient, lowercase letters should be consistently preferred in URI paths.

Do not use trailing forward slash (/) in URIs
Use hyphens (-) to improve the readability of URIs (Spinal-Case)
Do not use underscores ( _ )
Use forward slash (/) to indicate a hierarchical relationships

HTTP methods
Key objectives of the REST approach is using HTTP as an application protocol. Hence, we should systematically
use HTTP verbs to describe what actions are performed on the resources and facilitate the developer’s
work handling recurrent CRUD operations.

The following methods are used in REST development.

The GET method is used to retrieve information from the given server using a given URI.
Requests using GET should only retrieve data and should have no other effect on the data.

Same as GET, but transfers the status line and header section only.

A POST request is used to send data to the server, for example, customer information,
file upload, etc. using HTML forms.

Replaces all current representations of the target resource with the uploaded content.

Update a part of a document/content.

Removes all current representations of the target resource given by a URI.

Describes the communication options for the target resource.

Singular vs Plurals
commonly-accepted practice is to always use plurals in node names to keep your
API URIs consistent across all HTTP methods

Idempotent and Safe Methods
Some HTTP methods are considered Safe(does not change data) and Idempotent(can be called multiple time without side effect) and some are not. Following table summarizes the methods those are considered Idempotent and Safe.


An idempotent method means that the result of a successful performed request is independent
of the number of times it is executed.
For example
A = 2 + 3 ; is idempotent , because it does not matter how many times this statement is executed,
value of A would be always 2 +3 = 5
Where as
A = A + 3 is not idempotent since, on each execution the value of A will change (increase).

Safe Methods:
Safe methods are HTTP methods that do not modify the resource e.g. a GET, HEAD, OPTIONS are  safe because they doesn't modify the resource.
Where as other HTTP methods e.g. POST, PUT, PATCH, or DELETE are non-safe

HTTP Status Code

The RESTful Web Service should respond to a client’s request with a suitable HTTP status response code.
2xx – OK – everything is fine.
4xx – client error – if the client did something wrong (e.g. the client sends an invalid request or he is not authorized)
5xx – server error – something went wrong in the server, like the Database is down or  some exception was raised
by application server

2xx: Success
200 OK
201 Created
3xx: Redirect
301 Moved Permanently
304 Not Modified
4xx: Client Error
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
410 Gone
5xx: Server Error
500 Internal Server Error
List of HTTP status code can be found here

HATEOAS stands for Hypermedia As The Engine Of Application State 

Monday, September 25, 2017

Java Constructor vs method

Functionally difference between constructors and methods is that constructors create and initialize objects that don't exist yet, while methods perform operations on objects that already exist.

Constructors can't be called directly. They are invoked implicitly when the new keyword creates an object.
Methods can be called directly on an object that has already been created with new.

Constructors must be named with the same name as the class name.

Constructors cannot  return anything, even void .

Methods must be declared to return something ( or void).

Constructor compiler provide default constructor where as method compiler does't provide.

Constructor cannot be final since it cant be inherited.

Constructor cannot be abstract since it is used to create and initialize object.

Constructor cannot be static since it is used to create instance of object.

Only public, protected & private modifiers are permitted.

Tuesday, May 9, 2017

immutable objects in java

In software programming, an immutable object is an object whose state cannot be modified after it is created.

How to make Immutable Object in Java

  • Make the class final.
  • Make all members final, set them explicitly, in a static block, or in the constructor.
  • Make all members private.
  • Do not expose any setter methods.
  • If the instance fields include references to mutable objects, then don't share references to the mutable objects. 
  • For getter methods which needs to return mutable objects, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
  • Do not store references to external mutable objects passed to the constructor. Create copies, and store references to the copies. 

Advantage of Immutable Objects

Immutable Objects are ThreadSafe.
Value Objects are generally considered Immutable. In java String and all the Wrapper Classes like Integer, Boolean are immutable.
It enhances security and less bug when the object we are designing is not supposed to change value.
Immutable objects are better Keys and values for HashMap and HashSet respectively.

Friday, January 13, 2017

Better ways to implement Singleton in Java

Singleton Design pattern restrict creation of only once instance of a Class. That means inside a single JVM only one instance of the Singleton Class will be created.  In java we have broadly two options to implement Singleton.

1) Early Creation of the Object Instance.
2) Lazy Creation of the Object Instance: Here the instance is created on first invocation.

Following example demonstrate how to implement Singleton in Java.

Method 1: Early Creation of Object Instance
public class SingletonClass {
private static final SingletonClass INSTANCE = new SingletonClass(); //Private Constructor private SingletonClass() { //Do nothing } public static SingletonClass getInstance() { return INSTANCE; } }
Here the instance is created ahead even before calling the Class. We need to provide a private constructor otherwise Java Compiler will add a default Constructor.

Method 2: Lazy Creation of Object Instance
public class SingletonClass {
   private static volatile SingletonClass INSTANCE = null;
private SingletonClass() {
       //Do nothing
public static SingletonClass getInstance() { if (INSTANCE == null) { synchronized (SingletonClass.class) { if (INSTANCE == null) { INSTANCE = new SingletonClass(); } } } return INSTANCE; } }
In Lazy creation apporach the instance of the Class will not be created unless the getInstance() method is called. The above implementation we are checking if the INSTANCE is null twice, once before the synchronized block and once after the block. This is known as  Double - Checked Locking. The volatile keyword here is very important and would work only in Java 5+.

Above examples one can still create multiple instances under the following conditions,
1) Cloning the Object from the Object returned by Singleton.
2) Serializing and Deserializing.
3) If multiple Class loader are used in an Application then each Class Loader can have multiple instance of the same object.

We can extend the above two example  to take care (1) and (2 )
by  prevent cloning(Implement Cloneable interface) and throw Exception from clone() method.
Serialization by implementing  (Serializable Interface) and implementing readResolve() method to return the instance.

Other simple and better option is using Java enum. If we use Enum then we do not have to take care of Clone or Serializable issues. JVM make sure enum instances are Singleton in a single Class Loader.

public enum SingletonClass {
 //Which is equivalent to 
public final class SingletonClass { 
  public final static SingletonClass INSTANCE = new SingletonClass(); 

Monday, June 29, 2015

Java on Mac

Listing all installed Java
/usr/libexec/java_home -V

Matching Java Virtual Machines (5):
    1.8.0_45, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home
    1.8.0_25, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home
    1.7.0_51, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home
    1.6.0_65-b14-466.1, x86_64: "Java SE 6" /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
    1.6.0_65-b14-466.1, i386: "Java SE 6" /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

Selecting a particular version
/usr/libexec/java_home -v 1.8