Sunday, November 18, 2018

Circular Dependencies In Spring


Circular Dependencies In Spring


In order to understand the circular dependency scenario, we need to first understand "How Spring Inject Dependencies" in normal situation.

How Spring Inject Dependencies - Normal Situation

Let's take an example:
In our application we have beans A,B & C and they are depend on one another like below.


This is how spring resolve dependency injection process for our example scenario:


Above process illustrates by below code snippet. Here is our Main application :
Bean Files:

But...How It Works In Circular Dependency Situation ?

For the simplicity ,Lets assume A and B two beans are depend like below:



What Happen Next??

when having a circular dependency, Spring cannot decide which of the beans should be created first, since one bean depend on one another. In those type of situations , Spring will complain my throwing "BeanCurrentlyInCreationException" while loading the application context. 

But "I am not getting such exception?? Here is my code "




Yes..In this case you are using field level dependency injection.So spring is intelligent to identify such kind of scenario and it can fix the issue by itself.

  • Create Bean A & B first
  • Inject dependencies to each other 
This is how spring documentation states the problem:

 
References:

Wednesday, November 7, 2018

RMI IN ACTION


RMI (Remote Method Invocation)

RMI was most widely used technology(protocol) in old days to JAVA to JAVA distributed application communication since JDK 1.1. Although now a day’s most of web-based applications use modern technologies like REST based web-services, still we SHOULD NOT FORGET to learn those type of old technologies because they will help you to understand the modern solutions.  And by understanding those type of old technologies, you can easily understand, why design patterns, new architectural styles comes in to play.

Scenario: 

Volta is a weather forecasting company which have several data collection centers to collect weather data to predict accurate weather forecasting to its country citizens. Initially Volta’s head office collects its sub stations data using manual documentations. Due to this manual system, their predictions are not very up to date. So company management decided to automate their manual process. They have signed an agreement with One Soft Solutions to implement automated system.

Figure 1.1 Weather Station




John works for One Soft Solutions as a senior engineer. One Soft Solutions asked John to design an approach to address the above issue. In this situation, John have to face following problems:
  • Almost all the One Soft Solutions software engineers are busy with new projects except few java engineers.
  • Those non-busy engineers are not familiar with newer technologies like REST.
  • Client asked for demo within couple of weeks.
  • Solution should be expandable and should have ability to migrate to newer technologies after other developers are come in to play.
First of all John decided to explain RMI communication process in high level and then he created a documentation by including high level steps to to fallow to complete the project.

 Figure 1.2 RMI Communication Workflow

Step 01 :Designing and implementing the components of your distributed application.


    • Create Remote Interface (WeatherStation.java)
    • Implement the Remote Interface (WeatherStationImpl.java)
    • Implement the Client

Step 02 :Compiling sources

Step 03 :Making classes network accessible

Step 04 :Start the rmiregistry

Step 05 :Starting the server and client applications




Step 01 :Designing and implementing the components of your distributed application

Create Remote Interface

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface WeatherStation extends Remote {
                public String updateTodayConditions(
                                                                                      String subStation,
                                                                                       float temp,
                                                                                       float humidity,
                                                                                        float pressure
                                                                                  ) throws RemoteException;
}

Implement the Remote Interface

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class WeatherStationImpl extends UnicastRemoteObject implements WeatherStation  {
                protected WeatherStationImpl() throws RemoteException {
                                super();
                }
                public String updateTodayConditions(
                                                                                      String subStation,
                                                                                      float temp,
                                                                                      float humidity,
                                                                                      float pressure
                                                                                   ) {
                                System.out.println(
                                                                     "Sub Station :" + subStation +
                                                                     " Temparature :" + temp +
                                                                     "  Humidity :" + humidity+
                                                                     "  Pressure :" + pressure
                                                                  );
                                return "Success";
                }
}

WeatherStation Main Class

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;

public class Server {
                public static void main(String []args) throws RemoteException, MalformedURLException{
                                WeatherStation data = new WeatherStationImpl();
                                Naming.rebind("rmi://localhost:5000/WEATHERDATA",data);
                                System.out.println("Server Started..!!");
                                               
                }
}

Client Main Class

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

public class Client {

                public static void main(String []args) throws RemoteException, MalformedURLException, NotBoundException{
                      WeatherStation weatherData=(WeatherStation);
                       Naming.lookup("rmi://localhost:5000/WEATHERDATA");
                       String response=weatherData.updateTodayConditions("Station A",29,81, 54.1f);
                        System.out.println(response);

                }

}
















Step 02 :Compiling sources

Note:Before compile Client.java,you need to put remote interface (WeatherStation.class) to client folder. Client will invoke it as remote proxy.

Step 03 :Making classes network accessible

You need to allow client to access Server Stub's at run-time.Other wise server will throw remote exceptions.

Step 04 :Start the rmiregistry

Go to root folder of class folder and start rmiregisty by giving the port number.
 "start rmiregistry 5000"

Step 05 :Starting the server and client applications

Start Server program 1st and then start the client program.



You have done.

Next:I will explain one of the famous design pattern in my next blog post.Then you will understand why we learned this old jargon.

References:

Friday, August 31, 2018

Program to Nearer Future




As loving programming, we code software systems daily. But did you think about the future validity of your program .Sorry… "Near Future".


Sometimes our code may give big trouble when the systems scale up. Scaling your system may be from 2 users to 100 or 100000..00 users. You could say "we could not think about the Far Future because of project timing constraints". You are right. But remember to think for Near Future.


This is an example for illustrate the practice:

Lets say we have list of persons.


“Now  write a code to print person last names which start with the letter “Y””

If you are working with legacy system (before java8) your solution may look like below(java 8 solution will present at the end of the topic).  


But we know, when we going to apply that in real industrial environment we need to move those logics in to separate methods (in order to reduce code complexity).So we can write the same code as below:



But If we need to print persons which name start with H? Are you going to create separate method for that?(printLastNameStartWithH() etc.).You may say


...Noop……That’s not a good solution.First I change the method name and use generalized name and I can use additional argument to externalize filtering input. Then passing the filtering string, we can achieve your requirement.



But in near future if want to filter by lastNameStartWithM & lastNameStartWithH while keeping lastNameStartWithY ?
hmm..I need to create a separate method for that. Otherwise getting trouble now…

No still you need not to implement separate method for that.You can fallow this way;

Step 01:Create interface with test method


Step 02: Use anonymous inner class to implement filtering logic



In here we can change filtering logic as what we want. If we want to filter by lastNameStartWithM & lastNameStartWithR ,no need to change conditionalFilter methods’ signature. You can change the implementation of Condition interface as below.


 Now your code becomes:

If you familiar with java 8 ,no need to create separate interface for the above requirement. In java 8 , we have Predicate functional interface and lamda for that. Below is the java 8 solution.

So always try to program “NEAR FUTURE”. Sometimes his journey may not be simple to beginner. You have to learn and follow several things , specially including Design Patterns and Design Principles.