Sunday, May 28, 2017

Installing NGINX on macOS

I have heard of a lot of NGINX recently. One of them was it can help for security issues; for sure, it much be more. It so happens that our team has got a ton of user stories from a security audit. It's time to delve into it.

What is NGINX?


In order to get a basic idea and have some fun, I've just picked some available posts from my favorite Vietnamese blogger communities as below:
NGINX (pronounce: Engine-X) is a web server (comparing to IIS, Apache). It can be used as a reverse proxy (this is what I need for security issues with configuration), load balancer and more.

How to get started?


I found the below path for learning NGINX by googling "learn nginx":
In this post, I only went first step. This is installing NGINX on macOS and taking a first look at the configuration.

Installing


I used HomeBrew to install NGINX. If you are familiar with Ubuntu, HomeBrew is like an equivalent to apt-get on macOS.

Install HomeBrew

$ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Install NGINX

$brew install nginx

Run

$nginx

Test

http://localhost:8080/


Configuration


I still have no idea how to do configuration properly but I guess we need to modify something on some configurable files. The below might be an example. I'll keep trying hands-on in next steps.

$vim /usr/local/etc/nginx/nginx.conf

Saturday, May 20, 2017

Today I Learned - Git at First Glance

Getting Started


It's always fun to jump right in to the "HelloWorld" app. Just go for it!

Visit: https://try.github.io/levels/1/challenges/1

Cheatsheet


It's time for us to store our "magic tools".



Visit: https://www.git-tower.com/blog/git-cheat-sheet

Which collaboration way fit your team?


Git is just a tool which doesn't teach you how to work properly in a team. It depends on your projects and you need to choose your own team workflow.

Visit: https://www.atlassian.com/git/tutorials/comparing-workflows

Sunday, May 14, 2017

Make Our Code More Testable with Proxy Design Pattern

If you heard about the term separation of concerns, you could agree this concept is very important for making a system "clean". One of the most important characteristics of a clean system is testable.

Let me tell you my story about how I've just come acrosss the design pattern Proxy.


Note: to get started, you can find a very simple example of the pattern Proxy here.  

Let's start!


I have an interface as below:
public interface DocumentGenerator {
    File generate(Document document) throws BusinessException;
}

The following is my first implementation for a concrete class of DocumentGenerator.
public class DocumentGeneratorImpl implements DocumentGenerator {
 private Dossier dossier;
 private Locale locale;
 
 public DocumentGeneratorImpl(Dossier dossier, Locale locale) {
  validateNotNullParams(dossier, locale);
  this.dossier = dossier;
  this.locale = locale;
 }
 
 private void validateNotNullParams(LibertyDossier dossier, Locale locale) {
  if(Objects.isNull(dossier)) {
   throw new IllegalArgumentException("Dossier must not be null!");
  }
  
  if(Objects.isNull(dossier.getDossierType())){
   throw new IllegalArgumentException("Dossier type must not be null!");
  }
  
  if(Objects.isNull(locale)) {
   throw new IllegalArgumentException("Locale must be defined!");
  }
 }
 
 @Override
 public File generate(Document document, boolean temporary) 
  throws BusinessException {
  setCobIdForDossierIfNotExist();
  switch (dossier.getDossierType()) {
  case TYPE_A:
   // Do some logic here in case TYPE_A
  case TYPE_BA:
   // Do some logic here in case TYPE_B
  default:
   throw new BusinessException("Not supported dossier type");
  }
 }
 
 private void setCobIdForDossierIfNotExist() {
  if(StringUtils.isEmpty(dossier.getCobId())) {
   String generatedCobId = DossierService.getInstance().generateCobId();
   dossier.setCobId(generatedCobId);
  }
 }
}

The client code constructs the concrete class DocumentGeneratorImpl.
DocumentGenerator  generator = new DocumentGeneratorImpl(dossier, locale);

I saw that some private methods "validateNotNullParams(dossier, locale)" and "setCobIdForDossierIfNotExist()" are just a second responsibility of class DocumentGeneratorImpl.

Follow "S" of SOLID  - Single Responsibility


Firstly, I was thinking about how to separate these methods into another class. Then, I create a class called DocumentGeneratorHelper which contains to these methods. It was just improved a bit.

public class DocumentGeneratorImpl implements DocumentGenerator {
 private Dossier dossier;
 private Locale locale;
 
 public DocumentGeneratorImpl(Dossier dossier, Locale locale) {
  DocumentGeneratorHelper.validateNotNullParams(dossier, locale);
  this.dossier = dossier;
  this.locale = locale;
 }
 
 @Override
 public File generate(Document document, boolean temporary) 
   throws BusinessException {
  DocumentGeneratorHelper.setCobIdForDossierIfNotExist();
  switch (dossier.getDossierType()) {
  case TYPE_A:
   // Do some logic here in case TYPE_A
  case TYPE_BA:
   // Do some logic here in case TYPE_B
  default:
   throw new BusinessException("Not supported dossier type");
  }
 }
 
}

However, if I create tests for DocumentGeneratorImpl, I need to mock DocumentGeneratorHelper. Huh....! Any better approach?

I was thinking about that it is somehow I need to apply an Aspect-Oriented Programming (AOP) approach. As my google searching result, there are some approaches but they are quite complicated and heavy. They use Java Proxy or AOP Frameworks such as AspectJ.

A Simple AOP Approach


Fortunately, the keyword "proxy" leads me to the pattern Proxy. The idea of Proxy is really simple and cool!



Okay, now I create a Proxy instead of a Helper as before.

public class DocumentGeneratorProxy implements DocumentGenerator{
 private DocumentGenerator generator;
 private Dossier dossier;
 
 public DocumentGeneratorProxy(Dossier dossier, Locale locale) {
  validateNotNullParams(dossier, locale);
  this.dossier = dossier;
  this.generator = new DocumentGenerator(this.dossier, locale);
 }

 private void validateNotNullParams(Dossier dossier, Locale locale) {
  if(Objects.isNull(dossier)) {
   throw new IllegalArgumentException("Dossier must not be null!");
  }
  
  if(Objects.isNull(dossier.getDossierType())){
   throw new IllegalArgumentException("Dossier type must not be null!");
  }
  
  if(Objects.isNull(locale)) {
   throw new IllegalArgumentException("Locale must be defined!");
  }
 }

 @Override
 public File generate(Document document, boolean temporary)
   throws BusinessException {
  setCobIdForDossierIfNotExist();
  return generator.generate(document, temporary);
 }

 private void setCobIdForDossierIfNotExist() {
  if(StringUtils.isEmpty(dossier.getCobId())) {
   String generatedCobId = DossierService.getInstance().generateCobId();
   dossier.setCobId(generatedCobId);
  }
 }

}

Done! DocumentGeneratorImpl  doesn't contain its second responsibilities anymore. These methods are tested by the Proxy and we don't need to mock in DocumentGeneratorImpl.
the public class DocumentGeneratorImpl implements DocumentGenerator {
 private Dossier dossier;
 private Locale locale;
 
 public LibertyDocumentGenerator(Dossier dossier, Locale locale) {
  this.dossier = dossier;
  this.locale = locale;
 }
 
 @Override
 public File generate(Document document, boolean temporary) 
   throws BusinessException {
  switch (dossier.getDossierType()) {
  case TYPE_A:
   // Do some logic here in case TYPE_A
  case TYPE_BA:
   // Do some logic here in case TYPE_B
  default:
   throw new BusinessException("Not supported dossier type");
  }
 }
 
}

So, instead of calling directly DocumentGeneratorImpl, we call DocumentGeneratorProxy in the client code as below:

DocumentGenerator  generator = new DocumentGeneratorProxy(dossier, locale);

Happy codings!

Sunday, May 7, 2017

Separate Constructing a System from Using It

In the real world, in order to use a building (hotel, supermarket, etc) we need to construct it first. This concern should be applied for software development as well.

Step by step, I would like to show you the issue about no separation of constructing and using it and then I'll give you some approaches to overcome this issue.

| Note: you can find the below demonstrated code here  


Take a Look the Following Simple Application


Used tools and technologies: Eclipse (Mars), JDK 1.8

I had an App which uses Controller. Controller uses Service (an interface). Finally, Service has one concrete class is DefaultService.
//package vn.nvanhuong.system.separationconstructing;
public class App {
 public static void main(String[] args) {
  Controller controller = new Controller();
  controller.doAction();
 }
}

public class Controller {
 private Service service;
 
 public void doAction(){
  System.out.println("doAction in Controller");
  getService().execute();
 }
 
 public Service getService(){
  if(service == null){
   service = new DefaultService();
  }
  return service;
 }
}

public interface Service {
 void execute();
}

public class DefaultService implements Service {

 @Override
 public void execute() {
  System.out.println("executing Default Service");
 }

}

Do you find any issue?


Okay. Now, we just pay attention on this piece of code.
public Service getService(){
 if(service == null){
  service = new DefaultService();
 }
 return service;
}

Have you ever thought that we might meet at least three following issues?
  • Compile error: if Controller could not find DefaultService.
  • Testing: if we want to test Controller, we need to mock DefaultService in case it is a heavyweight object
  • Right object: if Service has more concrete classes, DefaultService will not be always a desired object in all cases.
The root cause is that we had a hard-coded "DefaultService" as a dependency of Controller.


How to solve?


The problem is the solution! Instead, we construct the instance of Service at Controller, we move this code of constructing into another place. Yeah!

There are three approaches.

Separation of Main - Separating the constructing into "main"


//package vn.nvanhuong.system.separationconstructing.main;

public class App {
 public static void main(String[] args) {
  Service service = new DefaultService();
  Controller controller = new Controller(service);
  controller.doAction();
 }
}

public class Controller {
 private Service service;

 public Controller(Service service) {
  this.service = service;
 }

 public void doAction() {
  System.out.println("doAction in Controller");
  service.execute();
 }
}

Factories - Using design pattern "Abstract Factory"


We move the constructing into a place separating from the application code.

//package vn.nvanhuong.system.separationconstructing.factory;

public class App {
 public static void main(String[] args) {
  ServiceFactory factory = new ServiceFactory();
  Service service = factory.getService(ServiceName.CUSTOM);
  Controller controller = new Controller(service);
  controller.doAction();
 }
}

public class ServiceFactory {

 public Service getService(ServiceName serviceName) {
  if (Objects.isNull(serviceName)) {
   throw new IllegalArgumentException("service name must not be null");
  }

  switch (serviceName) {
  case DEFAULT:
   return new DefaultService();
  case CUSTOM:
   return new CustomService();
  default:
   return null;
  }
 }

}

public enum ServiceName {
 DEFAULT, CUSTOM
}

public class CustomService implements Service {

 @Override
 public void execute() {
  System.out.println("executing from Custom Service");

 }

}

public class Controller {
 private Service service;

 public Controller(Service service) {
  this.service = service;
 }

 public void doAction() {
  System.out.println("doAction in Controller");
  service.execute();
 }
}

Dependency Injection


We move the second reposibility of object Controller (constructing Service) into another object. Moreover, DI helps us solve dependencies passively.

I used Google Guice for this demonstration. Because I still wanted to use a Java project (in Eclipse) instead of Maven project so that I simply found needed jars on Maven Repository and included them into project's buildpath. They are "guice-3.0.jar", "cglib-2.2.1.jar", "javax.inject-1.jar" and ''aopalliance-1.0.jar".

//package vn.nvanhuong.system.separationconstructing.di;

public class App {
 public static void main(String[] args) {
  Injector injector = Guice.createInjector(new AppInjector());
  Controller controller = injector.getInstance(Controller.class);
  controller.doAction();
 }
}

public class AppInjector extends AbstractModule {

 @Override
 protected void configure() {
  bind(Service.class).to(CustomService.class);
 }

}

public class Controller {
 private Service service;

 public void doAction() {
  System.out.println("doAction in Controller");
  service.execute();
 }

 @Inject
 public void setService(Service service) {
  this.service = service;
 }
}

How do you think about the issues and solutions? Leave your comments down below. :)

--------------
References:

[1]. Robert C. Martin, Clean Code - A Handbook of Agile Software Craftsmanship, Chapter 11, Systems.
[2]. https://en.wikipedia.org/wiki/Abstract_factory_pattern
[3]. http://www.journaldev.com/2403/google-guice-dependency-injection-example-tutorial

Saturday, February 25, 2017

The Evolution of Team Collaboration




In my point of view, if a team has a good collaboration, team members will achieve the following:
  • To be more effective
  • To make work more enjoyable

I have been working for a company for nearly four years as an software developer. Working on various projects from maintaining existing systems to developing a substantial product resulted in me moving to new teams three times. Actually, my most stable team lasted only around three years. 

Every time I've moved to a new team, I have a chance to work with new members and a new team culture again. Indeed, I realize that there is a process of developing the team collaboration which gets better time by time. I think it is an evolution!

Sunday, November 27, 2016

Review - The Object-Oriented Thought Process, by Matt Weisfeld


In this post, I would like to point out what I understood after closing my eyes and thinking about what  exactly I have learned from this book. That means the layout of content does not follow the book.


From Procedural to Object Oriented


Once upon a time, there is an issue that it is very hard to test and debug in Procedural programming because the data is sometimes global and can be modified by multiple functions.

Object-Oriented (OO) programming addresses these problems by combining both data and functions into an object. That means only functions belong to the object can access its own data.

Let us check the below two different approaches for a case that we want to transfer information between clients and servers across a network.

-    Procedural programming: a client (browser) transfers a JSON data to a server which needs to know how to process with this data. In order words, a handshaking agreement must be defined for the client and server in order to work together.
-    OO programming: a server transfers a Java object/applet to a client and the browser has no idea of what object will do. When the object is loaded the browser just executes the function and uses the data contained within the object.

Sunday, November 13, 2016

Building a Wizard with Chain of Responsibility Pattern

What is the Idea?


We want to create a page that there are some steps and each step has its own business. Users are able to click on a step and its status could be changed. Primefaces owns a component "Wizard" but it it quite hard for us in order to apply our very specific and complicated business domain logic on each step; even we cannot click on a step of this component.

We somehow are able to use the component "TabView" works with a strong back-end mechanism. A backend mechanism! what do I mean? Yes, we need it because we want to abstract the behaviors of each step otherwise we will get trouble with many events handling. Obviously, each step has some behaviors  such as "next", "back" and "switch' are the same and they are related to each other; but the business of these behaviors can be different totally. That is where the pattern "Chain of Responsibility" can be applied.