A word on toString()

A word on toString()



Can you spot the problem?

AccountHolder.java



package com.example.toString;

import java.util.ArrayList;
import java.util.List;

public class AccountHolder {
   
   private String name;
   private List<Account> accList=new ArrayList<Account>();
   
   public void addAccount(Account acc){
      accList.add(acc);
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   @Override
   public String toString() {
      return "AccountHolder [name=" + name + ", accList=" + accList + "]";
   }

}


Account.java
   
   
package com.example.toString;

public class Account {
   
   private String accNumber;
   private String accType;
   private AccountHolder holder;
   public String getAccNumber() {
      return accNumber;
   }
   public void setAccNumber(String accNumber) {
      this.accNumber = accNumber;
   }
   public String getAccType() {
      return accType;
   }
   public void setAccType(String accType) {
      this.accType = accType;
   }
   public AccountHolder getHolder() {
      return holder;
   }
   public void setHolder(AccountHolder holder) {
      this.holder = holder;
   }
   @Override
   public String toString() {
      return "Account [accNumber=" + accNumber + ", accType=" + accType
              + ", holder=" + holder + "]";
   }
   
   
   

}



Testing above

Main.java

package com.example.toString;

public class Main {
   
   public static void main(String[] args) {
      AccountHolder ach = new AccountHolder();
      ach.setName("Shamik Mitra");
      Account acc = new Account();
      acc.setAccNumber("100sm");
      acc.setAccType("Savings");
      acc.setHolder(ach);
      ach.addAccount(acc);
      System.out.println(ach);
   }

}



I believe you guess the problem. If you do not spot the problem please stop here and again go through the code to spot the problem.



What is the Problem?

The above code snippet, unfortunately, gives you a StackOverflowError.

While reviewing a juniors code I spotted the problem, Actually, his program runs well in the Development environment and he came to me to review his code.


To explain the essence of the problem I replicate the same here, I have an AccountHolder Object which holds the list of Account and on another hand In Account Object, we have a reference to AccountHolder.

This is a normal scenario when we design JPA entity, But the problem is we blindly populate the toString method using the editor and which create a circular call and eventually it blows up the code with StackOverflow Error.

As AccountHolder toString it tries to print the list of Account so it calls  Account toString() and in Account toString() it again tries to prints  AccountHolder so the cycle continues until StackOverFlowError occurs.
My Junior can’t spot the problem as in his program he never prints the Account or AccountHolder object so it deployed and works fine in Development server.


So what is the Point?

The point I want to convey here is that maybe this type of problem always can't be seen in naked eyes as may be there is transitive dependencies like A class has B, B has C and C has A.

So ,

  1. Try use tools which can point out your circular dependencies.(Though I am not using any due to some constraints).
  2. In a class, only prints variable which are belongs to that class. For safety purpose not print any HAS-A relation.
















Spring: Be careful when using PropertyPlaceholderConfigurer

A word on PropertyPlaceholderConfigurer

A few days back one of my juniors came to me and said that when he test his modules separately in JUnit that worked perfectly but when the modules were deployed in Server as a unit, Server fails to start.


So I checked his code and fortunately identified the problem.
in this Article, I will discuss  that problem.

Let me describe the problem in detail.
Problem Statement:

The application he works on has three layers.

1.Dao layers
2.Service layers.
3.Middleware(Spring MVC).


Which is very standard architecture, and each layer built on top of spring so maintains separate Spring context files.

Each layer maintains its own property file.

Say for  Dao layers database connection related properties are maintained in  db.properties.
In Service layer, web service URL or other service parameters are maintained in service.properties file.

To load these properties files in application it uses PropertyPlaceholderConfigurer in each SpringContext file (Dao, Service, Middleware).




Sample example

db.properties
db.url=abc@localhost:1028/BillSchema
db.user=admin
db.password=tiger


and the entry for PropertyPlaceholderConfigurer in Spring_DB_Context.xml

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="locations">
           <list>
               <value>classpath:db.properties</value>
             </list>
       </property>
      </bean>



Same for Services

Service.properties

bil.user=admin.
bill.passwd=abcd

and the entry for PropertyPlaceholderConfigurer in Spring_Service_Context.xml
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="locations">
           <list>
               <value>classpath:service.properties</value>
             </list>
       </property>
 </bean>


In middleware, Spring context Spring_Middleware_Context.xml   imports  Spring_DB_Context.xml and Spring_Service_Context.xml


Now when he runs each modules Junit test it can resolve the properties files and works fine, but the problem kicks in when middleware application combine other two modules as jar and import context files into Spring_middleware  context and try to deploy in Server.

It Shows an error message {db.url} can’t resolve, and server fails to start.


So, His question is why it is happening?
In Junit, it runs but when we clubbed two modules as a jar and try to deploy it on server why such error message, as we have provided the PropertyPlaceholderConfigurer in each context and both properties files are present in classpath.


Actual Problem:

Upon viewing the error message one thing is clear that somehow those properties are not resolved by PropertyPlaceholderConfigurer.

Now deep dive to Spring context to understand why it is not resolved?

There are three separate Spring context files

Spring_DB_Context.xml
Spring_Service_Context.xml
Spring_Middleware_Context.xml


Spring_DB_Context.xml,Spring_Service_Context.xml joins the big context Spring_Middleware_Context.xml while deploying, via import statement in Spring_Middleware_Context.xml.

And each context has it’s own PropertyPlaceholderConfigurer and a property file. Now, if the Service context is loaded first by classloader then it’s PropertyPlaceholderConfigurer is loaded and it properties files so this PropertyPlaceholderConfigurer can resolve the beans under Service context but won’t able to resolve the properties of DB_Context as Service PropertyPlaceholderConfigurer does not knows about that db.properties  file. So server says {db.url } can’t resolved.

Same is true for service layer if classloader load Db Context first the {service.url} can’t be resolved.


Solution

The solution is just a tweak in PropertyPlaceholderConfigurer in each context. Just add the following line

<property name="ignoreUnresolvablePlaceholders" value="true"/>


So, Updated context files

Service context

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="locations">
           <list>
               <value>classpath:service.properties</value>
             </list>
       </property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
 </bean>


DB context

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="locations">
           <list>
               <value>classpath:dbproperties</value>
             </list>
       </property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
 </bean>


By doing this we tell Spring to ignore the unresolved properties or put it in another word
By default, Spring throws an exception if it can’t resolve a property that is fail-fast in nature.
But here we will explicitly say to Spring don’t throw the exception but go on with unresolved properties defer the action so when other PropertyPlaceholderConfigurer(Db Context)  will be loaded it will resolve the other part.

NB: Please note that for each context you have to mention
<property name="ignoreUnresolvablePlaceholders" value="true"/>, unless if one context does not provide aforesaid tag it will fails there immediately as by default Spring is fail-fast.

My juniors case  was very similar like this although he provides <property name="ignoreUnresolvablePlaceholders" value="true"/> in every modules still it fails.

Then I search for transitive dependencies on its module and found that one of the modules does not define <property name="ignoreUnresolvablePlaceholders" value=" true"/> tag in its context so it fails there, we update the same and recompile it then all problem just gone like magic.


TIP: Always use <property name="ignoreUnresolvablePlaceholders" value="true"/>, with PropertyPlaceholderConfigurer  as you never know when and how other modules use your modules and they may have their own  PropertyPlaceholderConfigurer as well, So you can break their code unknowingly  and give them an opportunity to scratch their head.

Hello, Hexagonal Architecture

Hello Hexagonal Architecture


While developing a software we always craving for Architecture because we want our software adopts future changes easily.

So, Architecture stepped in for maintainability. Here maintainability mean how easily we can incorporate changes without disturbing old.

Every feature addition in a software comes with a Risk, Risk of breaking old,maintainability,rigidity,dependencies etc, There are many shades of risks
we called it Technical debt.


Technical debt has an inverse relationship of maintainability, using Architectural style we want to decrease the risk or I can say make it constant while adding new features.

We experienced that when we start writing code at that time it is easy to add features and gradually it becomes hard unless we do not use proper architecture for that software.


Hexagonal Architecture:

We will discuss Hexagonal Architecture here, in one word Hexagonal Architecture says.

Core business logic talks to other through a contract.

The core business logic means your software development logic should talk to others means Database or any JMS Queues or any Flat files or HTTP request or FTP , NOSQL etc through a contract or in Java language we can say interface.

The benefits of above type of design is whatever the input or output channels that boil down to the contract so every channel has to implement that contract/interface to talking with our software, So for our software perspective all are same as all implement the same contract so our software can deal with any types of input and output channel .

Benefits:

1, Easily incorporates any channel like Flat file,RDBMS, NoSQL, Http,Ftp,JMS etc.
2. Our software can be easily tested because it is easy to create a mock as just need to implement the contracts.

3. Adding new requirements means plugging it, or implementing the contracts.
4. Proper separation of concern.
5. Maintains IOC as Higher level and lower level talking through contract.


Sometimes we called Hexagonal architecture as Port and Adapter or Onion architecture.

As in this architecture, we have a port for each channel say for Database

The tasks we have to perform

To implement the contract to talk with our software.
As database API say JDBC is itself a contract or Hibernate is itself a framework so we need to create an adaptor GOF adapter pattern where we have to implement a strategy which converts JDBC related operation to our contract related operation.
Then plug this adaptor into our port to talk with this channel.



Outline of the design

Software Contract

package com.example.architecture.hexagonal;

public interface IPersists<T,TCOMMAND> {
   
   public void save(T t,TCOMMAND commandObject);    
   public void delete(T t,TCOMMAND commandObject);
   

}

This is the general contract for talking with our software, any output channel like File channel, RDBMS,NoSQL should implement that contract.


Here I take an example How it can talk to JPA entity which saves that data in Database.

DataBaseChannelAdapter.java
package com.example.architecture.hexagonal;

public class DataBaseChannelAdapter implements IPersists<EmployeeDomainObject,EmployeeCommand>{

   public void save(EmployeeDomainObject t, EmployeeCommand commandObject) {
     
       String underLyingJPAEntity = commandObject.getEntityClass();
       System.out.println("call save on " + underLyingJPAEntity);
     
   }

   public void delete(EmployeeDomainObject t, EmployeeCommand commandObject) {
       String underLyingJPAEntity = commandObject.getEntityClass();
       System.out.println("call delete on " + underLyingJPAEntity);
     
   }

}


As JPA Entity use some JPA related annotation so I did not include this JPA entity as part of our Domain, I use JPA framework as an Outside Channel of our software domain and DataBaseChannelAdapter takes our core domain Employee Object and takes a Command Object which tells Adapter to Which JPA entity to call and call the same.


EmployeeDomainObject

package com.example.architecture.hexagonal;

public class EmployeeDomainObject {
   
   public String name;
   public String address;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   @Override
   public String toString() {
      return "EmployeeDomainObject [name=" + name + ", address=" + address
              + "]";
   }
   
   

}


Our core Domain Employee Object it does not dependent on any Framework so I can plug any framework with it through Adapter like I can easily change DatabaseAdapter to FileAdepter to save our core domain object in File.




EmployeeCommand.java

package com.example.architecture.hexagonal;

public class EmployeeCommand{
   
   public String entityClass;

   
   
   public String getEntityClass() {
      return entityClass;
   }

   public void setEntityClass(String entityClass) {
      this.entityClass = entityClass;
   }

   @Override
   public String toString() {
      return "EmployeeCommand [entityClass=" + entityClass + "]";
   }

   
   

}





This Command object is nothing but help Adapter to convert Core Domain Object to Underlying Output channel (Database or File)

EmployeeDomainDao.java

package com.example.architecture.hexagonal;

public class EmployeeDomainDao<T,TCommand>{
   
   IPersists<T,TCommand> adapter;
   
   
   public void save(T t,TCommand commandObject)
   {
      adapter.save(t, commandObject);
   }
   
   public void delete(T t,TCommand commandObject)
   {
      adapter.delete(t, commandObject);
   }

   public IPersists<T, TCommand> getAdapter() {
      return adapter;
   }

   public void setAdapter(IPersists<T, TCommand> adapter) {
      this.adapter = adapter;
   }
   
   
   

}
This is our Core Domain Persist layer here I use the adapter as Strategy based on the Adapter it will call exact output channel and persist our Domain Object.





Now Time to Test our Software design


Main.java

package com.example.architecture.hexagonal;

public class Main {
   
   public static void main(String[] args) {
      EmployeeDomainDao<EmployeeDomainObject,EmployeeCommand> dao = new EmployeeDomainDao<EmployeeDomainObject,EmployeeCommand>();
      IPersists<EmployeeDomainObject,EmployeeCommand> adapter= new DataBaseChannelAdapter();
      dao.setAdapter(adapter);
      EmployeeDomainObject emp = new EmployeeDomainObject();
      emp.setName("Shamik Mitra");
      emp.setAddress("India,Kolkata");
     
      EmployeeCommand command = new EmployeeCommand();
      command.setEntityClass("com.employeemanagement.entity.EmployeeJpaEntity");
     
      dao.save(emp, command);
      dao.delete(emp, command);
   }

}








Output:

Object StateEmployeeDomainObject [name=Shamik Mitra, address=India,Kolkata]
call save on com.employeemanagement.entity.EmployeeJpaEntity
Object StateEmployeeDomainObject [name=Shamik Mitra, address=India,Kolkata]
call delete on com.employeemanagement.entity.EmployeeJpaEntity





Hexagonal Layers :






Hexagonal architecture,port & adapter architecture,onion Arhitechture

Picture courtesy Google



Application Domain: As I said earlier it is the software where all software related business logic, validation goes on, this is the inside module every outside module talks with it through contract.

Application/Mediation Layer:  Kind of services layer it adopts the Framework layer or ut’s outside layer and make necessary changes according to domain layer contract to talks with Domain layer or in the same way return back the result from Domain to Framework layer.
It sits between Framework and Domain layer.


Framework Layer: This layer as to input/output channel or we can say the outside world and use an adaptor to adapt the data and transform it according to our  software contract.