Dec 28, 2013

Spring Data REST - Sample application


In this post I will discuss how to create a sample MVC application with RESTful services and how to consume them. I am using Spriing 3.2.
Spring Data Rest : Export JPA enitites to web.
This application is not a complete application, but I will prepare an application, make it running, and we will get success response, persistence, and transnational.

I refrerred - http://www.petrikainulainen.net/spring-data-jpa-tutorial/
for guidance and created project using project shared on above site.

Major Steps include -
1. Install Maven, Eclipse, and tomcat
2. Create Maven project, and make it dynamic.
3. Complete code.
4. Deploy and run.
Step 1 is lengthy and Step 3 is tough.

Lets assume you have completed Step 1 and 2. And maven path is set in Eclipse.
Window->Preference->Maven->Installations
and also Window->Preference->Maven->User Settings
And move to Step 3. And create a maven project.
I named it SpringDataRest. Right Click -> Properties -> Project Facets -> Check "Dynamic Web Module".
And my package structure is like -

com.spring.datajpa.config
 - to hold configuration java files

com.spring.datajpa.controller
 - to hold controllers

com.spring.datajpa.dto
- to hold DTO, which is passed to UI

com.spring.datajpa.model
- to hold entities which are mapped to DB tables

com.spring.datajpa.repository
- to hold Spring Data repository. One repository for one entity

com.spring.datajpa.service
- service layer

Inside src/main/resources we have properties.





com.spring.datajpa.config
In Spring 3.2, we don't need web.xml. We do all configuration in java class.  WebApplicationInitializer - Interface to be implemented in Servlet 3.0+ environments in order to configure the ServletContext programmatically as opposed to traditional web.xml approach.
DataJPAInitializer - extends WebApplicationInitializer, DispatcherServlet is created and initialized. Also ApplicationContext.class is registered. ApplicationContext must have @Configuration
ApplicationContext - Configures Spring application context - DataSource, Transaction Manager, Entity Manager Factory, Message Source resource bundle, and ViewResolver.

I know it looks bit extensive when I have to create multiple classes for one entity - Person, but its like that in Spring Data -
Person - @Entity, @Table(name="persons")
PersonRepository - extends JPARepositiry; this provides CRUD behavior to entity.
PersonDTO - A DTO object which is used as a form object in create person and edit person forms.
PersonController - Dispatcher servlet will forward all requests to controller. Controller operations are mapped to HTTP actions.
PersonService  class exposes operation over Person.

I have updated the server.xml in tomcat: path="/" for SpringDataRest.

So, communication happens like -
JSP - Controller - Service - Repository - DB.
H2 is used as DB, and Hibernate as JPA provider.

Since, this is my first application using Spring data, I have just followed the conventions and suggestions.  But this application makes familiar withe whole Spring setup : Spring Data, Spring MVC, and REST service.

I have uploaded the Eclipse workspace. I believe just any one needs to download the zip file and unzip and make it the eclipse workspace. Check server settings, like tomcat installation path, port should be 8080.
Please download the workspace form below location -
https://www.dropbox.com/s/a8dpxqhwwebbzg1/SpringData.zip



Share:

Dec 27, 2013

REST & RESTful service, and why use REST


REST is Representational State Transfer. A client-server communication over HTTP. REST service is indeed a service with all service features like -
1. Platform independent
2. Language independent
3. Standards based - runs on HTTP.
4. Can be easily used - standard HTTP actions
with some benefits over SOAP services -
1. REST can be consumed by any client - even web browser with Ajax and JavaScript
2. Its light - doesn't requires XML parsing and doesn't require a SOAP header
3. SOAP is old and REST is newer
4. Common actions - HTTP GET, POST, PUT, DELETE
5. Every API behaves same - so everyone likes it.
6. Technologies of REST are well understood.
7. Its cool - Google, yahoo, amazon, twitter, flickr, uses it,
AND
8. REST is how web should be - stateless, cache-able.

Some things where SOAP will get precedence over REST -
1. Operations represent logic
2. Very loose coupling
3. Designed for distributed architecture, computing - loosely coupled distributed messaging
4. Very much standard(WSDL) with lot of WS-* guidelines and even standard error messages
5. Supports stateful and asynchronous calls.
etc.

But if you ask me the features of SOAP which are not present in REST are the reasons why we use REST.
We don't need arbitrary operation names, arbitrary actions(verbs).
We need to handle the tight coupling in REST, we can have minimal inter-dependencies in REST client an server, also sometimes the tight coupling results in optimized design(sometimes), and minimizes redundancies.
Right now we assume a Client-server architecture and don't think about lot of distributed systems.
We hate standards when they are too much. I don't like complex service descriptor WSDL.
And how many times we use Stateful, Transactional and asynchronous SOAP web services. Web services are most of the times assumed to be stateless and synchronous. But if you need complex system with stateful, transactional, and asynchronous web services then you should go for SOAP.

Before we start with some more theories about REST, lets look at some basic concepts -

  • HTTP
  • J2EE Design & Layered Architecture
  • SOAP to REST



                                     HTTP 
  • Browser is the client and web server gives response. An HTTP client opens a connection and sends a request message to an HTTP server; the server then returns a response message, usually containing the resource that was requested. 
  • HTTP is used to transmit resources, not just files. A resource is some chunk of information that can be identified by a URL. 
  • After delivering the response, the server closes the connection - Stateless, No transaction. 
A HTTP Request -
GET /path/to/file/index.html HTTP/1.0
GET is the most common HTTP method/action/verb; it says "give me this resource".
The path is the part of the URL after the host name, also called the request URI.
The HTTP version always takes the form "HTTP/x.x", uppercase.

A POST request is used to send data to the server to be processed in some way. Its different from GET.
  • There's a block of data sent with the request, in the message body. There are usually extra headers to describe this message body, like Content-Type: and Content-Length:.
  • The request URI is not a resource to retrieve; it's usually a program to handle the data you're sending.
  • The HTTP response is normally program output, not a static file.
                
                        J2EE Design & Layered Architecture

After few years of inception, J2EE architecture was based on MVC. And it was success and its still very widely practiced. And in J2EE we used jsp, servlet, ejb and dao layer. We were writing these and divided them in to layers. And communication was happening like - 
JSP --> Servlet --> EJB --> DAO --> DB. And we can divide them in separate boxes, Like below - 
Source - http://www2002.org/CDROM/alternate/478/
But in actual when any architect was designing a system, he or she was thinking about many design patterns and several layers came up, means apart form presentation, business, and dao,  many layers arised for many concerns like security, loose coupling, and to adhere to design patterns like service locator, business delegate, facade, etc. We saw many design patterns for J2EE application - 
Source - http://www.corej2eepatterns.com/

To follow design patterns and for separation of concerns, we came up with multiple layers, so I am desining a Hospital application i can assume of few layers, irrespective of some decisions like I will be using which framework, I will be using which ORM. But at least I can assume there will be a 
  • DAO/ORM layer
  • Business layer to hold business logic along with several business objects &mappers
  • Service facade layer to expose business logic as web service or probably as session facade
  • Executer layer to call services along managing transaction, logging, and other aspects. 
  • Controller/Action layer, where request will come first
  • Presentation layer consisting of JSP or now xHTML. 
I am assuming I have been given a task to design a Hospital application and considering the past experience, practices, patterns I have below design in mind - and design is irrespective of technologies i will use - 

So, I have a hospital application which allows to book appointment.
Probably, I will follow below major steps -
1 - Create DB. Write DAO/JPA layer. Write a business layer over it. Write web service over it. Name operations according to functionality like openSlots, bookSlot, etc. Generate WSDL and give to client application. Also we will have to add mappers to map service request/response to Business Objects, DTO's,/Entities.
2 - I will generate Client stubs using WSDL and import in my client application. I will also have controller and executer layer to call web service and to process browser requests. And mapping Form bean's to service request and response.
I designed the application but it seems to me very complicated and very difficult to maintain and extremely troublesome to explain any new developer who joins when application is ready -
1. Mapping actions. Mapping HTTP action to controller and then mapping controller to executer to web service call and so on.
2. Mapping objects like form bean to service request to business objects to entity.
3. Many layers.
You can say why are we have web service layer here.  But since re-usability was in my mind -
Assume, We have two applications, one which is used by customers and one is used by staff and both will have only: presentation + controller+executer only. Both applications will call common service's. Thats why I have kept service layer and beyond in separate application.

                                  SOAP to REST

Why not think of directly calling the web service form HTML. And map the HTTP action like POST, GET to actual Database opetation's like Select, Update.
When I call GET the webservice is called which fires select in DB and return just one row.
When I call POST the webservice is called which fires select in DB and updates just one row.
When I call DELETE the webservice is called which fires select in DB and updates just one row.
AND
we use the row as object for all communications so that we never map. Directly pick the row from DB and pass the entity to form, and form directly updates the Entity and calls POST and row is updated in DB.
Presentation also made easy we just convert the entity in JSON when passing to browser, and browser returns JSON which is converted to Enitity.
So, why not directly communicate with SLOT table directly get rows and update a row. 
We will have to services which return actual resource and directly talk to resource not to some operation which will further call some layer to update the resource. 

So, we started thinking of moving from SOAP to REST.
This thinking is similar to -   Richardson Maturity Model  (must read)
Read more about the maturity model on - http://www.crummy.com/writing/speaking/2008-QCon/act3.html
Martin flower has explained in much more simpler words -
http://martinfowler.com/articles/richardsonMaturityModel.html
And there is very informative implementation of REST on -
http://blog.safaribooksonline.com/2013/09/30/rest-hypermedia/

In my next post I will build a REST application in Spring.

Share:

Dec 16, 2013

My Videos

Useful videos created/uploaded by me - 


Web Service development using RAD in WAS7



JMS Queue creation in WebSphere Application Server -




Message Driven Bean(MDB) in RAD listening to WAS JMS Queue - 


Please comment if any doubt
Share:

Dec 13, 2013

Pune - Things to do in and around Pune





In Pune 

Living and Working in pune is good because this city offers multiple options to spend weekends and never get bored. Its hub of IT industries in India. But city has so much to offer -

Must Do in City -
M.G. Road ( Take coffee at MARZ-O-RIN, shop for souvenirs, buy cookies at Kayani Bakery(EAST Street beside M.G. Road), ice cream at Kwality(beside  Kyani Bakey), and Buffet at Dorabjee(also you can shop here). All these are very old shops.
Laxmi Road, longest and very old commercial street.
Koregaon Park - House of Osho Rajneesh Ashram.
Parvati Hill(http://en.wikipedia.org/wiki/Parvati_Hill) is the most beautiful attraction of the city. Its a hilllock in center of the city, you climb up and watch whole city from the top. Also there are 5 temples on the top of the hill. I would suggest reach parvati hill by 5:30 or 6:00 PM, climb up, visit temples and watch whole city from the top, be careful it closes by 7:00 or 7:30 pm.
Go to IskonTemple on Sri Krishna Janamashtami( Hindu Festival) in the month of August.
Watch Dahi Handi also in August last, I watched at F.C.Road. I uploaded a videoalso of Dahi Handi at F.C. road.
Most memoable moment would be watching the Ganpati pandals in the first week of September., esp. Dagdu Seth Halwai Pandal near Laxmi Road.
Watch Laxmi Puja and crackers, lighting on Laxmi Road in October/November
From July to November on most weekends there would be horse race in Race Course( near MG Road). Price should be around 50 INR for few races like 7 races.

M.G.Road, and Koregaon Park are major attractions of the city for outsider.  
There are some famous places/attractions like Aga Khan Palace, Parvati and Bund Garden but might be disappointing. 

Must visit restaurants in city

If you are looking for nice food at reasonable price in pune, do visit following restaurants in city & they are classic with charm -
1. Darios in Koregaon Park - A must visit, since located beside Osho Ashram, very peaceful location, nice snacks, tea, coffee.
2. Marz-O-Rin in MG Road- snacks,nice location,  not good service, reasonable rates.
3. Kayani Bakery in MG Road - Amazing biscuits.
4. Blue Nile near MG Road - Nice Non veg food, perfect location, ambience not so good, but very quick service.
5. Sukanta near JM Road- Thali, quick service, locaion not so good, may have to wait in queue on weekends. Ambience crowded on weekends and at peak hours.
6. Dorabjee near MG Road - Nice food, unique flavor of non veg food, good place for shopping food items, nice location, ambience good, service good.
7. Malaka Spice in Koregaon park for South asian dishes.
8. Cafe Good Luck on F.C. Road 
9Durvankur in Tilak Road - Maharastrian thali
10. German Bakery in Koregaon Park
11. Sujata Mastani in Sadashiv Peth
12. Shabree in Hotel Parichay, FC Road
13. Chitale Bandhu in Sadashiv Peth
14. Blue Nile in Camp
15. Fish Curry Rice in Narayan Peth

Above were restaurants that are quite famous and legendary. Many 5 star hotels feature variety of restaurants. Other than that I believe Zomato is the right source for more restaurants guide.


Nice hotels to stay in Pune - There are many, I would recommend - 
1. Marriott Convention Center, S B Road, gives nice view of the city.
2. O hotel, Koregaon Park, nice location in Pune
Several 5 star category hotels such as Westin, Hyatt, etc. 
and Osho Guest house.


Around Pune - 

Lavasa City(within 50 kms)
Khadakwasla - Panshet (within 50 kms)
Panchagni-Mahabaleshwar(Panchagani - Mahabaleshwar)
Matheran
Konkan(Mulshi lake - Tamhini ghat - Konkan - beaches )
Kaas Plateau
Lonavala
Visit above all during rains. 

One can also visit -
Prati Shirdi(Shirgaon) - A replica of Shirdi
Balaji temple - A replica of Tirupati Balaji. 
Shirdi
Adlabs Imagica Theme Park


Prati Shirdi - 




Lavasa - 

Lavasa is very close to Pune. If its raining it is very amazing drive. Nearly 30 kms of amazing drive to a beautiful place, a small town on the bank of lake surrounded by hills. Must visit if you are in pune and want a break. I drive to lavasa spend time there and come back. I never stayed there. One can spend night there and return next day. But I never preffered staying there, and hotels are costly and there is nothing much to do. May be in future they grow more and add more activities, at present there are not much activities apart from points, sight seeing, driving, and eating joints.
Eating
Ekaant is very famous and it is the first hotel/restaurant you would come accross in Lavasa, it is bit costly,one can take a view and drive down to lavasa city. There are plenty of options in lavasa to choose from alongside lake.
Drive
From Pune we drive to Paud road and take a left turn at some point to Lavasa, after you take left turn drive is best in pune. Drive for around 20 kms, you would cross a dam, and after another 5-10 kms you would enter lavasa city. I would suggest leave home early, you would get roads clear and also not much people at sights. Remember if you dont take left for Lavasa, you would be driving to Mulshi Lake and further to Tamhini Ghat and drive further 100 km and reach konkan sea beaches and dense forests.
Sight Seeing
If you home early you can stop at many places and wont find much crowd. First place to stop is DAM, which is Varasgaon Dam. Second after passing the DAM, you would find lake parallel to road, one can stop there. Thirdly after entering the Lavasa city stop after 100-200 meters. One more beautiful point to stop is either parking of Ekaant or outside Ekaant restaurant. and lastly is the lake in lavasa.

Lavasa -


Shirdi

WeekEnd Trip to Shirdi - Sai Temple and Shani Signapur

This would be one of the religious trip, a trip to temple of saint. And it brings complete satifaction and I felt my stay in Pune is complete after visiting Shirdi.
Shirdi is 180 kms from  Pune, one can travel by car or by bus.
We were four and we preferred train. An AC Sleeper coach, where you can sleep, we were four so we really enjoyed our journey, travelling, talking and enjoying the train ride. There are many trains from Pune to Shirdi. Remember there is a station, Sai Nagar Shirdi, SNSI which is about 2 km from Shirdi Temple. I went there in Sep., 2011, and Auto Rickshaw charged 10 INR to drom from Railway Station to Hotel, Pre book some hotel, but do research and find some one very close to Temple.
Day 1( Saturday ) -
 4:30 AM(around) catch train. Slept for few hours, woke up at 9:00, enjoyed ride till 11:00 AM, when we reached Shirdi.
Check in Hotel, Walked to Temple
1:00 PM - Reached temple, Roamed inside Temple, visited different temples like Shani Temple, Shankar temple.
               Performed "Mukh Darshan"(Near Gate No. 3). Booked for Narayan Pooja(100 INR for Sunday at 9:00 AM).
3:00 PM - Lunch at Prasadalai
4:00 PM - Went to hotel for some rest.
5:00 PM - Left for Shani Signapur( 70 km from Shirdi)
7 - 9:00 PM - Darshan of Shani Signapur, and village( famous for no doors at any door in village).
11:00 PM - Returned to hotel.

Day 2(Sunday)
8:00 AM - Reached Shirdi Sai Temple. Took VIP Pass for Darshan(Charges 100 INR, show ID Card), to skip the 3/4th of heavy queue and
               perform darshan of the famous deity.
9:00 AM - Attended Satya Narayan Pooja
11:00 AM - Joined Queue for Darshan( from three fourth).
2:00 PM - Khandoda Mandir, opp. to Sai Temple
If you are free and got some more time, please also visit Dwarka Mai Temple, near Gate No 4 of Sai Temple
3:00 PM - Prasadalai for lunch.
4:00 PM - left hotel for Station to catch the return Train to Pune.

Mulshi Lake - Tamhini Ghat - Karde Beach, Konkan

WeekEnd Drive to Konkan - Karde beach
There are many beaches in konkan, but based on some studies, blogs, forums, I found Karde is best and virgin beach in Konkan.

Mulshi Lake - Tamhini Ghat - Karde Beach (Dapoli, Konkan)
Total Distance - 270 km.
Dapoli is in Ratnagiri District. If you check the photograph, last photo in Slide Show. There are three ways to reach Dapoli.
Shortest one is 200 km.
There is one route through Mahabaleshwar also, which is a nice one.
One always plan going through one route and coming back through another. I went via Tamhini Ghat.
But If you have never been to Mahabaleshwar, you can plan going through Panchgani - Mahabaleshwar.
I planned come back to that route, but my driver its dangerous to return via mahabaleshwar.
If you plan to travel via Tamhini Ghat, your first stop should be - "Quick Bytes", Green Gate Resort. near Mulshi Dam.
take breakfast at Quick Bytes. And then walk to the back of "Green Gate Resort", to watch the Mulshi Lake. 

Another option is Basho, I don't exactly remember the name but it was similar which gives very nice view of lake - 

Then drive to Tamhini Ghat. There would be more than 50 waterfalls in Tamhini Ghat, worth watching. After Tamhini Ghat, you can drive to all beautiful sceneries that come along on the way to Mangaon, then Mahad, then Khed, and lastly Dapoli sequentially. After Reaching Dapoli, you would have to travel around 10 - 12 kms to reach the Karde beach, which is close to Murud Beach. There would be some hotels. I went there in August, 2011. Then there was no booking required. But also monsoons are off season. If one travels in November or December, you would need booking. I stayed in Sagar Sawaii, and paid 1200 INR per night. It was OK, but rest were too bad. Pick hotel carefully, food is concern there. One needs to places order 2-3 hrs in advance. Beaches there are not clean, only thing is Karde is not crowded, but rest are crowded, and bad. Soend Evening and morning at Karde Beach. Next morning, drive to Durga Temple, which is close to Murud beach, and on the way to Dapoli. Around 1.5 kms from Karde Beach. Its just another temple, Nothing special about its small wooden architecture and small Portugese bell. One can then travel to Anjarle, or if you want to come back go to Asud Bagh, which is on the way to Dapoli, and around 5 km from Karde Beach. Asud Bagh is amazing, you need to walk all along the bagh cross, river and climb up the mountain t watch a gomukh. Ig you want some adventure, do it. There is also a Ganpati temple in Asud Bagh. Other than that there is nothing much attractive. There are some forts which are either unattractive or you cant watch in MOnsoon season.
There is also Dolphin Watch on Karde Beach, but closed in Monsoon.
Best time to visit - November, December, January.

Mulshi lake - 

Konkan - 

Karde Beach - 


Choke Dhani

Choke Dhani located on Nagar Road is amazing place to spend your evening on weekend. It opens around 5:pm. There is a welcome "Tika", and as soon as you enter, you can find the ambiance of a Village, with lot of fun activities, and sights for photography. There are some games, shows, Camel, Bull, and Horse Ride, and Local food. Must visit for first timers. Place very close to Pune City. Good there is a free dinner which ethnic Rajasthani food. And best is they would give you souvenir when you leave. Enjoy the Rajasthani Village in Pune City. 


Panchgani - Mahabaleshwar
One Day Panchgani - Mahabaleshwar Trip

My Planned day trip plan was like -
---------------------------------


7 am - leave home9 am - panchgani ( Rajpuri Caves, TableLand, Parsi Point, Sydney Point)
           Trust me you can skip all(If you have seen lot of mountains), and wont regret.
12 am - Mapro( Snacks)


2 pm - Venna Lake
4 pm -  Mahabaleshwar Temple
5 pm - Arthur Seat Point
6 pm - Kate Point
7 pm - Mahabaleshwar Market
8 pm - Return to Pune


Panchgani - The Rajpuri Caves in Panchgani is a religiously important tourist spot. Lord Karthikeya temple is located at Rajpuri Caves in Panchgani.
Tableland has been credited with the privilege of being Asia’s second longest mountain Plateau.
Parsi Point is a renowned picnic spot lies on the Mahabaleshwar road in Panchgani.
Sydney Point would be the first point in Panchgai.
One might be disappointed at Tableland and Parsi Point. I went in rainy season, and Table land was full of horse dung. Sydney point is the first point while on the way to mahabaleshwar. One can skip, because there are many more points also. Rajpuri Caves are off the route.


Mapro is good place to buy mapro products and for snacks, there is a small garden also.
One can stay here for some time. I would suggest, rather than halting at any unknown restaurant/hotel on the way, stop here, eat really big, and tasty sandwich. Check small chocolate factory from outside, and small garden.

Venna Lake
Boating. Visit lake Venna for a ride on paddle/ or rowing boat.
You may ride boat on your own or, alternatively, you can hire one.
It is a beautiful and scenic lake.Horse Riding. You can hire horses for some riding at Venna Lake as well as in Table land( Panchgani).
If you go in rainy season, the lake might be closed.

Mahabaleshwar Temple is a nice religious tourist place, and there are total three temples close to each other.

There are around 25 points in Mahabaleshwar, one must watch Arthur Seat Point and Kate Point.
Actually close to Arthur's Seat there are 5 other points also.
Similarly close to Kate's Point, there are other points.

The most popular drink, available at most restaurants, is strawberry milk shake.  Spent some time in the evening in the market of mahabaleshwar, its good, and you would enjoy evening, and if you really like it much, stay a night there, and visit mahabaleshwar points next day, it would be better. You can definitely plan for two days. But since hotels were costly, and I didn't had time so I cam back by night. Also, in monsoon season, theres not much to do.

If you planing to spent night in mahabaleshwar, then you should also look at the tent stay in panchgani. Its really good, and there are several options(means several BnB's offering tent's), choose one.




Share:

Dec 11, 2013

Building Extendable/Flexible/Customizable J2EE Software Architecture with Spring


Software Architecture - Organization of system with components and how they interact with each other and environment. The whole system is build for some functions. When we draw a picture of this whole system, we want it to look good, we call it design, and a design can only look good if it follows some principles. The principles while tried and tested, and when we follow those principles while designing our system, we are giving guarantee in advance that system will be stable,  success and scalable.
Apart from stable, performance, and scalability, one of the important aspect about building a IT product is that it can be customized and extended.
I will discuss here an architecture, a system which is composed of multiple components/modules, and each module can be customized.

Develop a system with set of functions which will marketed as a product. Each new client can customize one or all the functions available.

I can say that system has some modules/functions; modules are integrated in one system; each module is designed in a manner that it can be extended; customization of one module doesn't affects other modules and integration of whole system; and packaging of one client doesn't includes customization's done for another.

When system designing started lot of thought process went for a long time regarding design, technologies to be used, modules, and regarding extensibility.

Its an online application. And one module will consist of some pages and controllers. And we can say a module is some page navigation's which complete one function. Like for example, a registration to a website involves some steps and end result is registration. Through a series of page navigation and some controller invocations, registration completes. And so we can consider "Registration" as one module. And then login/authentication a separate module. And one client can have separate fields mandatory while registration than another. One client can have separate pages/steps of registration than another.

Considering requirements and after some research Spring Web flow is winner for such a product -







  • Page flow of the application is visible just by looking at XML or java configuration.
  • Web flows are designed to be self contained, and thus are reusable multiple of times. 

  • Let me first discuss what is a flow and how can we visualize and implement it.

    What is a flow -

    Flow – A Sequence of steps – Part of application as a module
    Fund Transfer flow ->
    1. User chooses ‘Transfer & Payment’ from Account Summmary Screen.
    2. System will display the Fund Transfer fa├žade for user to choose an account (omit and jump to step 3 if user has only one account).
    3. System displays fund transfer input screen and asks user for beneficiary account information and transfer details.
    4. System validates the information and forwards user to confirmation page.
    5. Once user confirms the transfer order, a display-only result page appears with the updated data
    OR we can say:   Flow – Series of states: point in flow where something happens – view is displayed or action is executed




    For View, I have attached an xhtml(JSF) file, view file can be JSP or HTML or any other.



    All flow definitions used by Web Flow are added to registry.
                    webflow-config.xml

              Use the parent attribute to link two flow registries together in a hierarchy. When the child registry is queried, if it cannot find the requested flow it will delegate to its parent.
              FlowDefinitionRegistry loops through all flow registries in context and prepares a MAP with key as ID and value as FlowDefinition and stores in Cache.
              The key method is getFlowDefinition which takes a flow ID and returns a FlowDefinition for that ID.


    Dispatcher Servlet initializes the FlowHandlerMapping. On request servlet gets handler
    FlowHandlerMapping uses FlowURLHandler to get flow from URL. If FlowRegistry contains flowId, then returns a FlowHandler for flowId to Dispatcher Servle
    A request leaves the browser asking for a URL and optionally with request parameters.
    The request is first examined by DispatcherServlet.
    DispatcherServlet consults handler-mappings defined in a configuration file and selects an appropriate
    controller and delegates to it to handle the request.
    The controller applies appropriate logic to process the request which results in some information (a.k.a.
    model). This information is associated with the logical name of a result rendering entity (a.k.a view) and the
    whole is returned as a ModelAndView object along with the request back to DispatcherServlet.
    DispatcherServlet then consults the logical view name with a view resolving object to determine the actual view
    implementation to use.
    DispatcherServlet delivers the model and request to the view implementation which renders an output and sends it
    back to the browser.
    Servlet gets appropriate HandlerAdapter, invokes handlerAdapter.handle, which using flowExecuter executes the flow.

    Pink Square box is what can be extended and customized. 

    But before I discuss how I can customize the framework, I have a concept of giving each client an ID. 
    All the screen labels, messages, etc are coming from DB, and in each table I am keeping the ID as part of primary key so that message, screen label can customized according to each client. 

    Customizing Screen labels, messages, etc. for each client- 
    So, Like I want different error message for different clients for same business failure. 
    In MESSAGE table I will have entry with KEY, CLIENT_ID, and MESSAGE.
    And inside code I set the Client ID in application context, to that all queries include the CLIENT_ID as search criteria and appropriate message is picked. 

    Customizing/Extending Product feature for each client - 

    • Every feature is associated with a flow. 
    • All flows have ID. 
    • Any feature has a flow. 
    • Any feature which is not there in product is developed and made part of product while developing for client, which saves money also(upgrading product for free)
    • For any customization of any feature for any client, we extend the flow. 
    • We add Client_ID to the flowId when registering the extension flow in flow-registry. 

    So, if we have a flow with ID - register. 

    • We want to customize this flow for client abc. 
    • We have given client abc as CLIENT_ID as ABC.
    • We create a flow with ID as ABCregister which will extend the flow register. 
    • Only new states or changed states goes in extended flow(ABCregister), and rest things are picked form base flow(register). 

    How it works - 

    1. Both flows exist in the registry. 
    2. Registry is a HashMap with Key as flowID. 
    3. When user clicks on "Register" button on screen, the request URL contains the flowID, i.e. register. 
    4. System searches in the HashMap for the key, but it searches in order - 
    5. if(CLIENT_ID+flowID) exists return value against CLIENT_ID+flowID
    6. else return value against flowID.
    7. By default flow from the base product will be returned, unless we have extended the flow and registered that also. 
    8. If extended flow exists, then it will get preference. 

    Inside flows we refer the view state, which can be customized for each client.

    So, in flow I refer registerInput.html, and I want to customoze it for client abc. 
    I have registerInput.html as path com/product/register/registerInput.html
    I will place customized file at location - 
    com/product/register/abc/registerInput.html, also note my flow file path is - 
    com/product/register/register-flow.xml

    And I have wrote a custom resource(file) loader with logic - 
    Pick Client ID from application context. and search for - 
         clientId/viewName if not found then return - 
         viewName


    Bean extension –
              Extension architecture uses aspect class MultiClientExtensionLoaderAspect which contains a single piece of advice - “tryToInvokeCustomized”
              @Around("extensionPoint() && !isExtension() && !ignore()")
    public Object tryToInvokeCustomized(ProceedingJoinPoint pjp) {
                Object target = pjp.getTarget();
                Object extensionBean = findCustomizationForClient(target);
                if (extensionBean != null) { // if extension is found;
                    return invokeExtension(pjp, extensionBean);
                }
                Object retVal = pjp.proceed();
                return retVal;
         }
    findCustomizationForClient(target){
    String bean = target.getBeanName();
    extensionBean = extensionRepository.getExtension(bean groupId+businessID);
            if(extensionBean == null){
            extensionBean = extensionRepository.getExtension(beanName, groupId);
            }
    }
    Map> beanRepository( beanName, )

    So, my around advice works for all methods be it in action class, service class, or anywhere. It will look for first if any extended method otherwise invoke form base product. 
    Share:
    © Technology Strategy Architecture and Development | All rights reserved.
    Blogger Template Crafted by pipdig