An introduction to REST

REST (Representational State Transfer) is an architectural style for designing web services. REST provides a set of principles that define how Web standards, such as HTTP and URIs. are supposed to be used. When we follow the REST principles in designing our applications, these applications basically use Web’s architecture and get all benefits that come with it. These principles say:

We need to think in Resources

Resources are the fundamental building blocks of the web-based system.  A resource can be anything that we expose to the Web. It can be a document or movie clip or a product or a business process.

To use a resource like interacting with it on the network or manipulating it resource needs to be identifiable which means resource should get an ID. The web provides the URI (Uniform Resource Identifier) for this purpose.

A URI uniquely identifies a web resource and at the same time makes it addressable. Here are some examples of the URIs:
http://myapplication.com/customers/45679
http://myapplication.com/customers/45679/orders/123
http://myapplication.com/products/8889

A resource’s URI distinguishes it from any other resource. It gives us an opportunity to manipulate it using an application protocol such as HTTP.

The relationship between URIs and resources is many to one. A URI identifies only one resource, but a resource can have more than one URI just like a human can have more than one email address or telephone number.

resource

Resource Representations

Even though the above figure shows three representations with three URIs, multiple resource representations can be addressed by a single URI. Using content negotiation, consumers can negotiate for specific representation formats from a service. Consumers can use HTTP Accept request header with a list of media types they are prepared to process.

multipleresourcerep

A resource must have at least one identifier to be addressable on the web, and each identifier is associated with one or more representations. A representation is a transformation or a view of a resource’s state at an instant in time.

It is important to remember that a resource can have one-to-many relationship with its representations.

Resources needs to be linked together

When we browse the web to buy something, we navigate different page(s) by clicking links or completing and submitting forms. What we do basically, we perform a set of steps to achieve a goal, in this case to buy a product. It is the core concept of hypermedia: by transiting links between resources, we change the state of an application. There is a formal description of it: Hypermedia as the engine of application state (HATEOAS). The benefit of the link approach using URIs is that the links can point to the resources that can be provided by a different application, a different server, or event a different company.

Server provides a set of links to the client that enables the client to move the application from one state to the next by following a link. Links make an application dynamic.

Use of standard HTTP methods

The standard HTTP methods like GET, PUT, POST, DELETE need to be used correctly in order to make the clients interact with the resources. These are also called HTTP verbs. Their meaning along with some guarantees about the behavior is defined in HTTP specification. For example, GET should be used to retrieve a representation of a resource. GET is safe and idempotent which means a same request to get a representation can be issued multiple times. PUT is for updating a resource with the data or create it at this URI if it is not there already. DELETE is for deleting a resource. Both are unsafe but idempotent. POST is for creating a new resource which is neither safe nor idempotent.

When a safe method is invoked, the resource state on the server remains unchanged. An idempotent method can be invoked multiple times, the end result is the same.

Following the HTTP methods correctly is important because this makes our application part of the web.

Stateless communication

In REST, the server should not have to retain some sort of communication state for any of the clients it communicates with beyond a single request. It decouples the clients from the server which improves the scalability.

Advertisements
An introduction to REST

Builder Pattern

Builder Pattern is used to encapsulate the construction of a product and allow it to be constructed in steps.

Builder Pattern is an excellent design pattern when you are faced with many constructor parameters (more than 4). We have other options like having a constructor for each optional parameter or have a default constructor and rely on the Java Bean pattern, in which a setter and getter is provided for each attribute. But both of these options are ugly and error prone:

  • Multiple constructors is hard to read and open the possibility of passing the arguments in wrong order
  • Default constructor along with Java Bean pattern (getter & setter) suffers from below serious problems:
    • Object can be in an inconsistent state partway through its construction
    • It does not enforce consistency and validity checks

Builder pattern does not suffer from the above problems.

The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. – Gof

So instead of creating the desired object directly, the client calls a constructor with all the required parameters and gets a builder object. The client then calls chained (methods that return this) setter-like methods  on the builder to set the optional parameters of interest. Finally, the client calls a parameterless build method to create the object, which is always immutable.

Advantages:

  • Encapsulates the way a complex object is constructed
  • Allows objects to be constructed in a multistep and varying process
  • Helps to avoid long argument list
  • Helps to avoid mixing constructor arguments

Drawback:

  • Constructing objects requires more domain knowledge of the client than using a Factory.

Example:

public class Pet {
    public static class Builder {
        private final Pet pet = new Pet();

        public Builder withPetName(final String petName) {
            pet.petName = petName;
            return this;
        }

        public Builder withOwnerName(final String ownerName) {
            pet.ownerName = ownerName;
            return this;
        }

        public Builder withAddress(final String address) {
            pet.address = address;
            return this;
        }

        public Builder withDateOfBirth(final String dateOfBirth) {
            pet.dateOfBirth = dateOfBirth;
            return this;
        }

        public Builder withEmailAddress(final String emailAddress) {
            pet.emailAddress = emailAddress;
            return this;
        }

        public Builder withPhoneNumber(final String phoneNumber) {
            pet.phoneNumber = phoneNumber;
            return this;
        }

        public Pet build() {
            if(pet.petName == null) {
                throw new NullPointerException("Pet name is null");
            }
            return pet;
        }
    }

    private String petName;
    private String ownerName;
    private String address;
    private String dateOfBirth;
    private String emailAddress;
    private String phoneNumber;

    @Override
    public String toString() {
        return "Pet{" +
                "petName='" + petName + '\'' +
                ", ownerName='" + ownerName + '\'' +
                ", address='" + address + '\'' +
                ", dateOfBirth='" + dateOfBirth + '\'' +
                ", emailAddress='" + emailAddress + '\'' +
                ", phoneNumber='" + phoneNumber + '\'' +
                '}';
    }
}

 Test

public class PetTest {

    @Test
    public void validPetBuild(){

        Pet.Builder builder = new Pet.Builder();

        Pet pet = builder.withPetName("kiko")
                .withAddress("123 Main Street")
                .withDateOfBirth("12-02-1978")
                .withEmailAddress("test@hotmail.com")
                .withOwnerName("John")
                .withPhoneNumber("3434232")
                .build();

        Assert.assertNotNull(pet);
    }
}
Builder Pattern

Dependency Injection

Imagine we are going to develop an email composition system. We will use this system to compose and send the email. These are tasks we need to do:

  • Writing the message
  • Checking spelling
  • Looking up a recipient’s address
  • Send the email

We have the below objects responsible for doing these tasks:

  • TextEditor for writing the message
  • SpellChecker for checking spelling
  • AddressBook for recipient’s address
  • Emailer is responsible for sending the email

In this example, we can see Emailer depends on a TextEditor, a SpellChecker and an AddressBook to send the email. This relationship is called dependency. Here Emailer is a client of its dependencies – an object depends on the other objects. This is also called object graph.

Few more things to note here:

  • Service – An object that performs a well-defined function when called upon
  • Client – Any consumer of a service, an object that calls upon a service to perform a well-understood function.

They are also referred as dependency and dependent respectively. A client cannot function without its services. In other words, an object cannot function properly without its dependencies.

Let’s see how we can build the object graph without Dependency Injection.

public class Emailer {
   private SpellChecker spellChecker;
   
   public Emailer() {
      this.spellChecker = new SpellChecker();
   }
   
   public void send(String text) { .. }
}

Creating an Emailer with a SpellChecker is simple

Emailer myEmailer = new Emailer();

Now say we want to have spell checkers in different languages. This is certainly not possible with the above code because here Emailer encapsulates the creation of its dependencies. Moreover the above code is not testable because we cannot replace the internal spell checker that Emailer has with a dummy one.

Let’s improve this

public class Emailer {
   private SpellChecker spellChecker;
   public void setSpellChecker(SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }
   ...
   ...
}

In this code we have a method that accepts a SpellChecker. Now we can use different spell checkers in our Emailer. Let’s try a French spell checker:

Emailer myEmailer = new Emailer();
myEmailer.setSpellChecker(new FrenchSpellChecker());

What about a Japanese one:

Emailer myEmailer = new Emailer();
myEmailer.setSpellChecker(new JapaneseSpellChecker());

Now we can test it with a mock spell checker

Emailer myEmailer = new Emailer();
myEmailer.setSpellChecker(new MockSpellChecker());

This gives us the option to pick a suitable spell checker service (English, French, or Japanese) that suits our need. We could have done this with a constructor.

public class Emailer {
  private SpellChecker spellChecker;
  public Emailer(SpellChecker spellChecker) {
     this.spellChecker = spellChecker;
  }
  ...
  ...
}
Emailer myEmailer = new Emailer(new EnglishSpellChecker());

Here we are constructing the object graph ourselves, construction by hand. Though this is better than the previous one, still tedious. If we use the same object in many places, we must repeat the code for wiring objects in all of those places. Not only this if we want to alter the dependency graph or any of its parts, we may be forced to go through and alter all of its client as well. Another problem is that users need to know how object graphs are wired internally.

We can remove this concrete dependency by creating the dependency externally and inject into Emailer. The task of creating, assembling, and wiring the dependencies into an object graph is performed by an external framework (or library) known as a dependency injection framework or simply a Dependency Injection (DI).

Control over the construction, wiring, and assembly of an object graph no longer resides with the clients or services themselves.

Example of DI frameworks: Spring, PicoContainer, Guice.

Here is an example how we can do this using Spring

public class Emailer {
   private SpellChecker spellChecker;
   private AddressBook addressBook;

   public void setSpellChecker(SpellChecker spellChecker){
      this.spellChecker = spellChecker;
   }
   
   public void setAddressBook(AddressBook addressBook){
      this.addressBook = addressBook;
   }

   public void send(String text) {
     ...
   }
}
<beans xmlns=”http://www.springframework.org/schema/beans”
       xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
       xsi:schemaLocation=”http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd”>

       <bean id=”spellChecker” class=”com.roytech.EnglishSpellChecker” />

       <bean id=”addressBook” class=”com.roytech.OfficeAddressBook” />

       <bean id=”emailer” class=”com.roytech.Emailer">
                <property name="spellChecker" ref="spellChecker”/>
                <property name="addressBook" ref="addressBook"/>
        </bean>                                                                                                           
</beans>
Dependency Injection

Creating project using Maven

Maven is a tool used for building and managing any Java-based project. Maven helps in:

  • Making the build process easy
  • Providing a uniform build system. Maven allows a project to build using its project object model (POM) and a set of plugins that are shared by all projects using Maven, providing a uniform build system.
  • Providing quality project information. This information is taken from the POM and in part generated from the project’s sources. For example, Maven can provide change log document created directly from source control, cross referenced sources, unit test reports including coverage
  • Providing guidelines for best practices development such as keeping the test source code in a separate, but parallel source tree, using test case naming conventions to locate and execute tests, etc.
  • Allowing transparent migration to new features

Steps in creating project using Maven:

  1. Install Maven and Java. Test the Maven installation by running mvn from the command-line:

    mvn -v

    If installation goes well, you should see similar information like below about the maven installation:

    Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T12:57:37+01:00)
    Maven home: /usr/local/Cellar/maven/3.3.3/libexec
    Java version: 1.8.0_60, vendor: Oracle Corporation
    Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre
    Default locale: en_US, platform encoding: UTF-8
    OS name: “mac os x”, version: “10.10.5”, arch: “x86_64”, family: “mac”

  2. Now create a project from a Maven template. In the command-line navigate to the folder you want to create the java project and type the below command:

    mvn archetype:generate -DgroupId=com.roytech -DartifactId=goodnews -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

    It tells Maven to create a Java project from Maven maven-archetype-quickstart template. In -DgroupId we have given the group or organization’s name that the project belongs to. Often expressed as an inverted domain name. In -DartifactId we have given the project’s library artifact (for example, name of its JAR or WAR file).

  3. With mvn archetype:generate + maven-archetype-quickstart template, the following project directory structure is created:
    goodnews
    |------src
    |----------main
    |-------------java
    |---------------com
    |----------------roytech
    |-------------------App.java
    |----------test
    |--------------java
    |----------------com
    |-----------------roytech
    |-------------------AppTest.java
    |------pom.xml
    

    In simple, all source codes are in folder /src/main/java/, all test codes are in /src/test/java/. In addition, a standard pom.xml gets generated. This POM file contains the entire project information, everything from directory structure, project plugins, project dependencies, information related to project building, etc. It includes the following details of the project configuration:

    • modelVersion – POM model version (always 4.0.0)
    • groupId – Group or organization that the project belongs to. Often expressed as an inverted domain name
    • artifactId – Name to be given to the project’s library artifact (for example, the name of its JAR or WAR file)
    • version – Version of the project that is being built
    • packaging – How the project should be packaged. Defaults to “jar” for JAR file packaging. Use “war” for WAR file packaging

  4. Maven is now ready to build the project. You can execute several build lifecycle goals with Maven now, including goals to compile the project’s code, create a library package (such as a JAR file), and install the library in the local Maven dependency repository.

    To try out the build, issue the following at the command line:

    mvn compile

    This will run Maven, telling it to execute the compile goal. When it’s finished, you should find the compiled .class files in the target/classes directory.

    Since it’s unlikely that you’ll want to distribute or work with .class files directly, you’ll probably want to run the package goal instead:

    mvn package

    The package goal will compile your Java code, run any tests, and finish by packaging the code up in a JAR file within the target directory. The name of the JAR file will be based on the project’s and . For example, given the minimal pom.xml file from before, the JAR file will be named goodnews-1.0-SNAPSHOT.jar.

    If you’ve changed the value of from “jar” to “war”, the result will be a WAR file within the target directory instead of a JAR file.

    Maven also maintains a repository of dependencies on your local machine (usually in a .m2/repository directory in your home directory) for quick access to project dependencies. If you’d like to install your project’s JAR file to that local repository, then you should invoke the install goal:

    mvn install

    The install goal will compile, test, and package your project’s code and then copy it into the local dependency repository, ready for another project to reference it as a dependency.

  5. Understanding dependency in pom.xml.

    If you look into the pom.xml, there is junit dependency is present. Junit is used for unit testing.

    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
      </dependency>
    </dependencies>
    


    This block of XML declares a list of dependencies for the project. Specifically, it declares a single dependency for the Junit library. Within the “dependency” element, the dependency coordinates are defined by three sub-elements:

    • <groupId> – The group or organization that the dependency belongs to
    • <artifactId> – The library that is required
    • <version> – The specific version of the library that is required



    By default, all dependencies are scoped as compile dependencies. That is, they should be available at compile-time (and if you were building a WAR file, including in the /WEB-INF/libs folder of the WAR). Additionally, you may specify a <scope> element to specify one of the following scopes:

    • provided – Dependencies that are required for compiling the project code, but that will be provided at runtime by a container running the code (e.g., the Java Servlet API)
    • test – Dependencies that are used for compiling and running tests, but not required for building or running the project’s runtime code



    Now if you run mvn compile or mvn package, Maven should resolve the Junit dependency from the Maven Central repository and the build will be successful.

Creating project using Maven

OOP Concept: Polymorphism

Polymorphism means the ability to take more than one form.

For example, an operation may exhibit different behaviour in different instances.

PolymorphismPrinciples:

  1. A method defined in a class is inherited by all descendants of that class
  2. When a message is sent to an object to use method draw() , any messages that draw() sends will also be sent to the same object
  3. If the object receiving a message does not a have definition of the method requested, an inherited definition is invoked
  4. If the object receiving a message has a definition of the requested method, that definition is invoked

Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. This means that a general class of operations may be accessed in the same manner even though specific actions associated with each operation may differ.

Any Java object that can pass more than one IS-A test can be considered polymorphic. Other than object of types of type Object, all java objects are polymorphic in that they pass the IS-A test of their own type and for class Object.

Polymorphism is extensively used in implementing inheritance. In Java, a class cannot extend more than one class. That means one parent per class. However a class can have multiple ancestors. For example, class B can extend class A and class C can extend class B, and so on. So any given class might have multiple classes up its inheritance tree.

OOP Concept: Polymorphism

OOP Concept: Abstraction & Encapsulation

Abstraction refers to the act of representing essential features without including the background details or explanations.

Abstraction focuses on the observable behavior of an object. I have found this blog post that explains abstraction in more details : http://brevitaz.com/abstraction-in-java/

The wrapping up of data and functions into a single unit (called class) is know as encapsulation.

Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those functions which are wrapped in the class can access it. These functions provide the interface between the object’s data and the program.

The insulation of the data from direct access by the program is called data hiding.

Edward V. Berard in his article Abstraction, Encapsulation, and Information Hiding concluded saying:

Abstraction, information hiding, and encapsulation are very different, but highly-related, concepts. One could argue that abstraction is a technique that helps us identify which specific information should be visible, and which information should be hidden. Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible.

OOP Concept: Abstraction & Encapsulation

OOP Concept: Inheritance

Inheritance is the process by which objects of one class acquire the properties of objects of another class.

Inheritance
Inheritance

Inheritance supports the concept of hierarchical classification. In inheritance, each derived class shares common characteristics with the class from which it is derived. In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an exiting class without modifying it. We can achieve this by deriving a new class from the existing one. The new class will have the combined features of both the classes. Each sub-class defines only those features that are unique to it.


public class Bird {
    
    private String color;
    private String food;
    private String movement;
    public Bird(String color, String food, String movement) {
        this.color = color;
        this.food = food;
        this.movement = movement;
    }

    @Override
    public String toString() {
        return "Bird {" +
                "color='" + color + '\'' +
                ", food='" + food + '\'' +
                ", movement='" + movement + '\'' +
                '}';
    }
}

public class FlyingBird extends Bird {
    public FlyingBird(String color, String food) {
        super(color, food, "flying");
    }
}

public class NonFlyingBird extends Bird {
    public NonFlyingBird(String color, String food) {
        super(color, food, "walking");
    }
}

public class Robin extends FlyingBird {
    public Robin(String color) {
        super(color, "fruit");
    }
}

Declaring subclasses


public class B extends A {
  .....
}

  • means class B is a specialization of a class A
  • the is a relationship exits
  • a B object is an A object

Other Names:

  • Super class is also called “Parent class”
  • Sub class is also called “Child class”

Child class inherits characteristics of parent class:

  • attributes
  • methods

So when we say public class Robin extends FlyingBird { .. } then

  • a Robin object inherits all FlyingBird attributes
  • which, in turn, inherits Bird attributes

Remember, extends is unidirectional. A extends B does not imply that B extends A. For example:

Bird aBird = new Robin(“Blue”);

  • is legal
  • a Robin object is a Bird object

But Robin aRobin = new Bird(“Grey”, “Fruit”, “Flying”);

  • is not legal
  • a Bird object not necessarily a Robin object
OOP Concept: Inheritance