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 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 Development with Java background | All rights reserved.
    Blogger Template Crafted by pipdig