Skip to main content

Posts

Showing posts from January, 2018

Decorator design pattern

Greetings!

Decorator is a structural design pattern.

When we need to add extra functionality to an object it is normal to do it through inheritance. Depending on the number of functionalities we may end up higher number of class hierarchy which leads to maintenance nightmare.

Using Decorators we can add additional responsibilities using composition at run time. We do not have to modify existing class but we can "decorate" it to add extra functionalities.

Inheritance is one form of extension, but not necessarily the best way to achieve flexibility in our designs.

"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality."


Image source wikipedia

Let's see a sample,

Classes should be open for extension but closed for modification.

Template method design pattern

Greetings!

Template Method pattern is a behavioral pattern.

When we have a common steps to do something but some steps vary, we can do it using bunch of if else statements. But the problem is things are tightly coupled and when new things need to be added we have to change our class. This leads our class difficult to main. For these kind of problems Template Method can be used.

We can have a super class to handle our common steps and let sub classes to define their own implements.

"Defines the skeleton of an algorithm in a method, deferring some steps to sub-classes. Template Method lets sub-classes redefine certain steps of an algorithm without changing the algorithm's structure."


Image source wikipedia

A sample code

Don't call us, we'll call you. - allow low-level components to hook themselves into a system, but the high-level components determine when they are need and how.

Singleton design pattern

Greetings!

Singleton design pattern is one of the most commonly used pattern. It falls under creational patterns.

"Ensure a class only has one instance and provide a global point of access to it."

There are multiple ways to create a singleton class.
Eagerly initialization - instance of class is always created, whether we use it or not. (anyway we are creating a class to use it aren't we?)Lazily initialization - create the instance at first call. we have to deal with threading issues.Use of a holder - Bill Pugh method. use an inner class to create the instance hence create the instance lazily and can avoid threading issues. There are ways to break singleton behavior by force and few tricks to prevent them.
Cloning - implement clone() and throw an exception to prevent thisReflection - throws an exception in constructor to solve thisDifferent class loaders - implement getClass()

Observer design pattern

Greetings!

Observer design pattern falls into behavioral category.
This is useful when multiple objects(observers) needs to be updated according to another object's changes(subject).

Subject and observers are loosely coupled and have no knowledge of each other.

Subject(one) -> Observer(many)

"Define a one-to-many dependency between objects so that when one object changes state, all its dependencies are notified and updated automatically."



Image source wikipedia


Strive for loosely coupled designs between objects that interact.

Strategy design pattern

Greetings!

Strategy pattern is a behavioral pattern. It is one of the easiest patterns to learn.

From wikipedia
A class should be configured with an algorithm instead of implementing an algorithm directly.An algorithm should be selected and exchanged at run time. Algorithm here is not necessarily a mathematical algorithm.
It is usually defined as a procedure that takes some value as input, performs a finite number of steps and produces some value as output.
Simply a method that does a specific thing.

"Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it."


Image source wikipedia

Let's have a sample,

Encapsulate what varies.Favor composition over inheritance.Program to interface, not implementation.

Spring Generic RestTemplate

Greetings!

Springs comes with handy RestTemplate to consume REST APIs.
(baeldung site has a good resource about RestTemplate.)

I thought to create a generic wrapper to hide the RestTemplate usage so that others can use it without thinking about RestTemplate.

Here is the code. (in my case this is enough for now :) )

Introduction to Node

Node.js Node.js is an open-source, cross-platform, JavaScript runtime built on Chrome's V8 Javascript engine that allows developers to create all kinds of server-side tools and applications in JavaScript. Node.js was developed by Ryan Dahl in 2009.
https://nodejs.org/en/
Javascript everywhereGreat performanceAsynchronous and event drivenSingle threadedNode package manager (npm) provides access to thousands of reusable packages.Portable Express Express is an un-opinionated, minimalist web framework for Node.js
https://expressjs.com/
Setting up the Node environmentInstall Node $ curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
$ sudo apt-get install -y nodejs
$ node -vInstall express generator The express application generator tool generates an Express application skeleton.
$ npm install express-generator -g
(-g flag installs the tool globally)
Create skeleton project $ express --ejs --git hellonode
$ cd hellonode
$ npm install
$  DEBUG=hellonode:* npm start
then go to br…

Layouts in express ejs

Greetings!

This is the 5th part of our Node EMS.

In my last post I used the same html layout for all the views. But it is still repeating. So one solution for it to use a layout engine. For express ejs we can use express-ejs-layouts.

$ git clone https://github.com/slmanju/node-ems.git
$ cd node-ems
$ npm install
$ npm run devstart

If you like to check the changes done in this tutorial
$ git checkout layout-with-ejs
Installation $ npm install express-ejs-layouts --save
Usage in app.js we add following,
var expressLayouts = require('express-ejs-layouts');
app.use(expressLayouts);
app.set('layout', 'layout/main');

Then we create main layout file and use <%-body%> to generate final html. All other html files will have only the body content.
out final main.ejs

Creating views with EJS

Greetings!

This is the 4th part of Node EMS.

Express uses Jade/ Pug as default view template engine. But it is not pure html which is difficult for a non-ui guy.
We can change the view engine to EJS using --ejs option when creating the project.

Complete code for this tutorial,
$ git clone https://github.com/slmanju/node-ems.git
$ cd node-ems
$ git checkout create-views
EJS EJS is a simple templating engine that generate HTML with plain JavaScript. There is no special thing about that since it uses plain HTML and uses JavaScript like syntax to generate dynamic contents.
Supports includes, filtters, etc
Tags <% 'Scriptlet' tag, for control-flow, no output
<%= Outputs the value into the template (HTML escaped)
<%- Outputs the unescaped value into the template
<%# Comment tag, no execution, no output
<%% Outputs a literal '<%'
%> Plain ending tag
-%> Trim-mode ('newline slurp') tag, trims following newline
Create views We are going to use a …

Creating a controller in Node

Greetings!

In this 3rd part of the tutorial, we are going to connect our employee schema with the controller.

(this is incomplete without views on next tutorial)

We are going to use mongoose's built in methods to access database and do our operations.

Update employee controller as follow.

Creating models with mongoose

Greetings!

This is the 2nd part of our Node employee management system. In this part, we are going to create our model.
MongoDB MongoDB is an open source NoSQL database that stores data as documents in JSON like structure. A "collection" of "documents", in a MongoDB database, is analogous to a "table" of "rows" in a relational database.

This combination is extremely popular because it helps to use same structure in entire application. (thus creating stacks like MEAN)
Mongoose Mongoose is an Object Document Mapper(ODM) for Node. (like Hibernate for Java). It allows us to access MongoDB commands simply and easily.
https://www.npmjs.com/package/mongoose
Initialize database * You need to have installed Mongo in your computer.
go to the terminal and do this,
$ mongo
> use nodeems;
> db.employees.insert({
   firstName: 'Manjula',
   lastName: 'Jayawardana',
   email: 'manjula121@gmail.com',
   password: 'manju'
})…

Node employee management system

Greetings!

Let's do some practical thing using Node.

In this Node tutorial series we are going to build an Employee Management System.
Node introductionNode Employee Management System (EMS) setupCreating models with mongooseCreating a controller in NodeCreating views with EJSCreating layouts get the complete code
$ git clone https://github.com/slmanju/node-ems.git
$ cd node-ems
$ npm run devstart
navigate to http://localhost:3000




Generate the project $ express --ejs --git node-ems
$ cd node-ems
$ npm install
$ npm install nodemon --save
   update scripts: "devstart": "node ./bin/www"
$ npm run devstart

quickly check the setup: http://localhost:3000/

Let's modify the folder structure a bit. $ mkdir server
$ mv routes/ server/
$ mv views/ server/
$ mkdir server/controllers
$ mkdir server/models

> you need to modify the app.js to pick routes, views from server folder now.


Create new employee-controller in server/controllers
Create employee routes $ mv server/…

Logging with logback

Greetings!

It is important to add proper loggers into our application because when something bad happens, it is the way to gather related information.

There are multiple libraries for logging in Java like JUL, log4j, logback. Spring uses logback as the default library.
When we add any starter dependency that will add starter-logging as well since it depends transitively on the logging starter.

howto-configure-logback-for-logging

Complete source code, todoapp
$ git clone https://github.com/slmanju/todoapp.git
$ cd todoapp
$ gradle clean bootrun
Log Levels Log messages can be used in several levels.
ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF
If WARN is enabled, then WARN, ERROR, FATAL will be logged
Appenders Appenders responsible for writing log statements.
ConsoleAppender – writes messages to the system consoleFileAppender – appends messages to a fileRollingFileAppender – extends the FileAppender with the ability to roll over log filesSMTPAppender – sends log mess…

REST tutorial : security with JWT token

Greetings!

This is the last part of our security tutorial.
Complete source code
$ git clone https://github.com/slmanju/todoapp.git
$ cd todoapp
$ git checkout security

follow the complete tutorial
JWT JSON Web Token is an open standard that defines a compact and self-contained way for securely sharing data between parties using a JSON object.
Compact - smaller sizeSelf-contained - payload contains all the required information Typically contains,
Header - consists of the type of the token, hashing algorithm being usedPayload - contains the claims.Signature A token fields are separated by dots like this, xxx.yyy.zzz

https://jwt.io/introduction/

Since we already have added token support in our previes tutorial, we only have to modify it to a JWT token.


Sample Header {
  "alg": "HS512"
}
Sample Payload {
  "sub": "manjula",
  "userId": "1",
  "role": "ADMIN",
  "iat": 1515401468,
  "exp": 15154…

REST tutorial : security

Greetings!

So far we have created a nice looking REST API with Java tech stack. But it is missing a crucial piece. Security!!!

Complete source code, todoapp
$ git clone https://github.com/slmanju/todoapp.git
$ cd todoapp
$ git checkout security
Spring Security Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.
spring-security

Lets add spring security starter to our project.
compile('org.springframework.boot:spring-boot-starter-security')

$ gradle clean bootrun
$ curl -i http://localhost:8080/todos
You will get a message like this,
{"timestamp":1515304279482,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/todos"}

With just adding the library Spring has secured our application!

Have a look at the console log. You can see so…

REST tutorial : validations

Greetings!

Our API is all good but it currently accepts empty Todos. Let's fix that with validations.

You can find the complete source code here Todoapp
Hibernate Validator Hibernate Validator allows to express and validate application constraints.
Implements JSR 380 bean validation api.
Hibernate validator is entirely separate from the persistence aspects of Hibernate.
http://hibernate.org/validator/

Hibernate Validator 6.0 is the Reference Implementation of the Bean Validation 2.0 specification.
Steps:Update gradle compile('javax.validation:validation-api:2.0.1.Final')
compile('org.hibernate:hibernate-validator:6.0.7.Final') Update controller method to add @Valid checkUpdate TodoDto with validatorsCatch validation exception in global exception handler (MethodArgumentNotValidException) Useful annotations @Length(min=, max=) - check if the string length match the range
@Max(value=) - check if the value is less than or equals to max
@Min(value=) - check if the value …

REST tutorial : error handling

Greetings!

So far we have neglected error scenarios in our API. Any application without proper error handling is a disaster.

You can find the complete source code here Todoapp

Try these URLs and see the output.
http://localhost:8080/todoss
http://localhost:8080/todos/abcd

Spring has handled errors for us!! but the messages are not interesting enough.

Global exception handlingWith Spring's @ControllerAdvice we can handle exception globally. ResponseEntityExceptionHandler : A convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods. @RestControllerAdvice is a new feature of Spring Framework 4.3, an annotation with combined @ControllerAdvice + @ResponseBodyEnable spring.mvc.throw-exception-if-no-handler-found to customize 404 error
Note that our TodoService is also updated to throw a custom exception.
See the complete code in error-handling branch.

In next part of the …

REST tutorial : Controller layer

Greetings!

This is the last post of our RESTful webservice section 1 ;) . Previous part is here
We still have to implement error handling, security etc

You can find the complete source code here Todoapp

Step 1: Create TodoController annotated with @RestController


Step 2: Implement our methods. Spring will do the REST ;)


Let's test our service using Postman.
start the server, gradle clean bootrun

Test 1: Empty Todos
Note the status: since we do not have any Todos yet, it is 404



Test 2: Create a Todo
We get the 201 status and created Todo's location in header



Test 3: List Todos



Test 4: Update a Todo



Test 5: Delete a Todo




That is all for now, though it is working we are yet to handle errors properly and secure our end points.

REST tutorial : Create repository

Greetings!

This is the 2nd post of our tutorial series. Previous part is here
In this part let's create our domain quickly.

You can find the complete source code here Todoapp
Spring Data JPA Spring Data JPA improves the implementation of data access layers by reducing boilerplate codes. For the repository interfaces Spring provides the implementation automatically.
https://projects.spring.io/spring-data-jpa/

Lombok Lombok reduces boilerplate code for model objects. It can generate getter, setter, toString, hashCode, equals, constructors for you. https://projectlombok.org

To make it simple, we will have Todo with Id, title and summary.

Step 1: Modify database properties


Step 2: Create Todo model


NOTE: Lombok will eliminate getter, setter, toString, hashCode burden.

Step 3 : Create Todo repository


With magic of Spring that is all ;)

REST tutorial introduction

Greetings!

In this tutorial series, we are going to study RESTful services with Spring.

We are going to build a TodoApp in this series since it is one of the easiest way to touch the technical stack.

You can find the complete source code here Todoapp

For the simplicity i'm going split tutorial into smaller parts.
Section 1: CRUD IntroductionRepository layerService layerController layerSection 2: Error handling Exception handlingValidationsSection 3: Security Add token authenticationEnhance token with JWTSection 4: User interfaceSection 5 : Miscellaneous Logging with logback GoalCreate a RESTful service using Java tech stack. What you need Java 8Gradle 4IDE REST REST stands for REpresentational State Transfer. It is an architectural style rather than a strict protocol. Not a standard but a set of constraints, such as being stateless, having a client/server relationship, and a uniform interface. rest wiki Spring Framework The Spring Framework is an application framework and inversion …