Tuesday, February 12, 2013

Configure Weblogic JMS Resources


Before we can configure Weblogic JMS resources such as ConnectionFactory, Queue, Topic, it is better to understand some concepts in Weblogic JMS.  

JMS Server


JMS server is the management container for JMS resources defined in JMS modules targeted to.   A JMS server's main responsibility is to maintain persistent storage for these resources, maintain the state of durable subscriber and etc.
JMS servers are persisted in the domain's config.xml file and multiple JMS servers can be configured on the various WebLogic Server instances in a cluster, as long as they are uniquely named.
One domain can have one or more than one JMS server. 
A JMS server can manage one or more JMS modules.
One cluster node has own JMS server targeted to managed node.
For example there are two managed nodes in a clustered environment: osb_ms1 and osb_ms2.
We create two JMS servers: OSB_JMSServer_01 and OSB_JMSServer_02 which are targeting osb_ms01 and osb_ms02 respectively.

JMS Module


JMS modules group JMS configuration resources (such as queues, topics, and connections factories).  These are outside domain configuration.  
JMS module targets the servers.   If it is clustered environment it will target all servers in the cluster.

Subdeployment


Subdeployment is also known as Advanced Targeting.  
Subdeployment resource is a bridge between the group of JMS resources and JMS Servers.   Without Subdeployment the JMS resources cannot target any JMS server.
When you create a JMS resource you need to choose one Subdeployment.
In clustered environment one Subdeployment targets multiple JMS server for each cluster node.

The below diagram shows the relationship between them.


 

Steps to configure JMS resources


The following is an example which demostrate the configuration steps for JMS resources in Oracle using Oracle Weblogic Console. This example is done with a single node environment. 

 

1. Create JMS Server

The first step is to create a JMS server.  Select the domain in Console.  Then click on YourDomain-->Services-->Messaging-->JMS Servers. In the right panel click on New button. And then type in the name for JMS server to be created and select the Persistence Store.  If Persistemce Store doesn't exist create a new Persistence Store.   Then click on Next button.


Select the Weblogic server node and then click on Finish button.  Then a JMS server called Demo-JMSServer is created.  This Demo-JMSServer is targeted to AdminServer.















2. Create JMS Module

The second step is to create a JMS Module. Select the domain in Console. Then click on YourDomain-->Services-->Messaging-->JMS Modules.   In the right panel click on New button.  And then type in the name for JMS Module.  Then click on Next button.
 
 

 
Then select the target of Weblogic server node.


Then click on Next button.

Then click on Finish button.  DemoJMSModule is created.











3. Create JMS Resource

The third step is to create a JMS resource such as connection factory, queue or topic in above created JMS Module.
Click the JMS Module where a resource is created.


Then click on New button.


Select the resource type to be created.   Here we create a Queue.   Then click on Next button.


Type in the Queue nama and JNDI name for this Queue and then click on Next button.



Select the Subdeployment.  If no existing Subdeployment can be used click on Create a New Subdeployment buttn.





Type in the name for a new Subdeployment and then click on OK button.




Then select the JMSServer and then click on Finish button.


 
 
 


 

Sunday, February 10, 2013

Use Spring MVC Test framework and Mockito to test controllers

Recently I came into one project which is using Spring MVC for web-tier in the architecture.  It gave me a chance to use Spring MVC Test framework and Mockito mock framework together in the unit testing of all Spring MVC controllers in the application.   I found that both of them provide very good functionalities to test the controllers and would like to show what I did with them.

 

Spring MVC Test framework

Before when unit testing MVC controllers we usually use MockHttpServletRequest and MockHttpServletResponse and directly send this mock request to the controllers to do the unit testing, now in Spring 3.2 there is a new test framework which is specially used for testing Spring MVC.   It is Spring MVC Test framework.  With this test framework you can test your controllers just like you test them within a web container but without starting a web container.
Spring MVC Test framework provides much nicer testing framework to cover many aspects of testing in Spring MVC.   With this framework apart from testing business logic within controllers we can also test inbound/outbound request/response serialization (such as JSON request to Java and Java to JSON response), request mapping, request validation, content negotiation, exception handling and etc. 
 In order to use it you can add the below dependency into your project POM file.

    <properties>
        <spring.version>3.2.0.RELEASE</spring.version>
    </properties>
      
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>provided</scope>
    </dependency>

The key part of Spring MVC Test framework is MockMVC.  MockMVC will simulate the internals of Spring MVC and MockMVC is the entry point for Spring MVS testing.    
The first step of using Spring MVC testing is to instantiate one instance of MockMVC. 
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml",
                                                        "classpath:/META-INF/applicationContextForTest.xml"})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class})
public class ProductControllerTest {
   
    @Autowired
    private WebApplicationContext wac;
   
    private MockMvc mockMvc;
   
    @Before
    public void setup() {
        
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

        // Details are omitted for brevity
    }
}

After MockMVC is created you can use MockMVC to do the testing.    You can create one HTTP request and specify all the details of the request such as HTTP method, content type, request parameters and etc.   Then you can send this request through MockMVC and then verify the results.
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/welocme");
       
this.mockMvc.perform(requestBuilder).
                        andExpect(MockMvcResultMatchers.status().isOk()).
                        andExpect(MockMvcResultMatchers.model().attribute("welcome_message", "Welcome to use product: DELL Insprson")).
                        andExpect(MockMvcResultMatchers.model().size(1)).
                        andExpect(MockMvcResultMatchers.view().name("welcome"));


Mockito

Mockito is another testing mock framework.   I find that it is quite easy and convenient to use.   First if you want to use it in your project you can the following dependency to your project POM file.  Here I use the version 1.9.5.
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>

Mockito provides some annotations to simplify writing the testing codes.  @Mock and @InjectMocks are the two annotations I am going to use.   @Mock is used to annotate the object to be mocked.   In the unit testing when testing a method of one object which has the dependency on another object, this dependent object needs to be mocked.  In my project there is class called ProductController and another class ProductService. ProductController uses ProductService to do actual work to serve the requests ProductController is supposed to handle.
@Controller
@RequestMapping("/products")
public class ProductController {
   
    @Autowired
    private ProductService productService;
   
    // Details are omitted for brevity
}

When I test ProductController I have ProductService as mock service so it can mock different responses from ProductService.   Using @Mock annotation from Mockito it can simply be done in my test class as the below:
 @Mock
ProductService mockProductService;

Another step is to put this mock object into the object to be tested.  Mockito provides another very useful annotation @InjectMocks to do. @InjectMocks is to annotate the object where the mock object is injected into.   In my example it is ProductController. and I have the following:
@InjectMocks
ProductController productController;

But in order to make mock object injection really happen there is another thing needed to be done: invoke MockitoAnnotations.initMocks method.  So my test class will be as the below:
public class ProductControllerTest {
   
    @InjectMocks
    private ProductController productController;
   
    @Mock
    private ProductService mockproductService;
   
    @Before
    public void setup() {
       
        MockitoAnnotations.initMocks(this);
    }
}

The basic functions of mock framework is to return a given results when a specific method is invoke.   In Mockito it is done using Mockito.when(...).thenReturn(...) 
public class ProductControllerTest {
   
    @InjectMocks
    private ProductController productController;
   
    @Mock
    private ProductService mockproductService;
   
    @Before
    public void setup() {

        MockitoAnnotations.initMocks(this);

        List<Product> products = new ArrayList<Product>();
        Product product1 = new Product();
        product1.setId(new Long(1));
       
        Product product2 = new Product();
        product2.setId(new Long(2));
       
        products.add(product1);
        products.add(product2);
       
        Mockito.when(mockproductService.findAllProducts()).thenReturn(products);
    }
}

In the above example when findAllProducts method in ProductService is invoked the mocked ProductService will return a list of Products specified before.


Put all together


The below is the code snippet that shows using both Spring MVC Testing and Mockito together for testing a controller.

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml",
                                 "classpath:/META-INF/applicationContextForTest.xml"})
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class})
public class ProductControllerTest {
   
    @Autowired
    private WebApplicationContext wac;
   
    private MockMvc mockMvc;

    @InjectMocks
    private ProductController productController;
   
    @Mock
    private ProductService mockproductService;

   
    @Before
    public void setup() {

        MockitoAnnotations.initMocks(this);

        List<Product> products = new ArrayList<Product>();
        Product product1 = new Product();
        product1.setId(new Long(1));
       
        Product product2 = new Product();
        product2.setId(new Long(2));
       
        products.add(product1);
        products.add(product2);
       
        Mockito.when(mockproductService.findAllProducts()).thenReturn(products);
        
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

    }

    @Test
    public void testMethod() throws Exception {
       
        List<Product> products = new ArrayList<Product>();
       
        Product product1 = new Product();
        product1.setId(new Long(1));
       
        Product product2 = new Product();
        product2.setId(new Long(2));
       
        products.add(product1);
        products.add(product2);
               
        RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/products");
       
        this.mockMvc.perform(requestBuilder).
                andExpect(MockMvcResultMatchers.status().isOk()).
                andExpect(MockMvcResultMatchers.model().attribute("Products", products)).
                andExpect(MockMvcResultMatchers.model().size(2)).
                andExpect(MockMvcResultMatchers.view().name("show_products"));
       

    }
}







Saturday, February 9, 2013

How Spring MVC works

MVC is a very good design pattern which is widely used in applications with UI(Desktop or web).   In this pattern M is Model, V is the View and C is controller.   The advantage of design pattern is to separate the different responsibilities into 3 parts when dealing UI.   In general terms  Model represents the business data and logic, View is visual part where the data in Model is displayed and Controller is the link of Model and View.  Controller is the brain which decides what data is used and how data is viewed.    Each part in MVC has the clear and dedicated responsibly.   By using MVC pattern the applications with UI become easier to develop, modify and maintain. 


SpringMVC is a web framework provided by Spring based on MVC pattern.   This framework is built on top of JEE/Servlet and is request-driven.  So it means that some servelts will listen on some ports for the incoming request and each request will trigger the whole process of serving this request in MVC and the data or resources that the request asks for is presented.
The below shows the categories of SpringMVC using MVC terms.



In Spring MVC DispatcherServlet and Controllers act as the Controller and they receive the requests and decide how the request will be served and also decide which view is used.  Business objects and domain objects are the Model and the business objects are invoked by the controllers and the all data are in domain objects.   The domain objects will be passed to some JSP which are the View part.  The JSP will render the data in the domain objects.

DisptacherServlet

DispatcherServlet is the front controller in Spring MVC.   It is a HttpServlet that will receive the request and return the response.  DispatcherServlet is the key player in SpringMVC.  From the below brief work flow of SpringMVC you can see DispatcherServlet is the driving force that make the request served with the right response sent back to the client.    


  1. Receive the request from client
  2. Consult HandleMapping to decide which controller processes the request
  3. Dispatch the request to the controller   
  4. Controller processes the request and returns the logical view name and model back to DispatcherServlet
  5. Consult ViewResolver for appropriate View for the logical view name from Controller
  6. Pass the model to View implementation for rendering
  7. View renders the model and returns the result to DispatcherServlet
  8. Return the rendered result from view to the client
It is obvious that DispatcherServlet has a heavy workload.  It needs many other strategy objects and configuration to perform these work.   Each DispatcherServlet has its own specialized ApplicationContext: WebApplicationContext.


MappingHandler


One important work to be done before DispatcherServlet can dispatch the request to the Controller is to find out which controller is right one for this request.  DispatcherServlet uses MappingHandler strategy object to do so.   There are many MappingHandler implementations which uses different strategies to map the request to Controller.   By default DispatcherServlet will use BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping.

public interface HandlerMapping {
      HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}


Controller

After the mapping is resolved DispatcherServlet will dispatch the request to the Controller.  Controller does the real work of processing the request.  Also Controller is where programmers need to work most in developing SpringMVC applications.  Controller has the knowledge of processing the request and what logical view be used for different result of request processing.  Usually Controller doesn't do the real processing and it delegates the request processing to the service layer.   Another thing the Controller to do is to package the result of the processing into the Model, which will be rendered in the View finally.


ViewResolver

After the Controller finish the processing of request it will return the logical view name and the data to DispatcherServlet, which will decide the actual view to be used since the view name from Controller is logical name.   With the help of ViewResolver strategy object DispatcherServlet can find out physical view from the logical view name.   Similar to MappingHandler there are also many different strategies  for resolving the view based on the different view technologies.    Most commonly used implementation of ViewResolver is InternalResourceViewResolver.  

public interface ViewResolver {
      View resolveViewName(String viewName, Locale locale) throws Exception;
}


View

View is where the data in the Model is rendered as the required output for the client.   SpringMVC provides many implementations of View to generate different output such as JSP,Excel, PDF, XML and etc.   DispatcherServlet will invoke render method from selected View implementation to generate the output to be returned to the client.

public interface View {
      String getContentType();
      void render(Map<String, ?> model, HttpServletRequest request,  HttpServletResponse response) throws Exception;
}

Friday, February 8, 2013

Root WebApplicationContext and Child WebApplicationContext

SpringMVC uses one special ApplicationContext: WebApplicationContext in web application.   WebApplicationContext is the extension of ApplicationContext.   It has ServletContext and and beans in WebApplicationContext can access ServletContext if they implement the interface ServletContextAware.

In Spring ApplicationContext can be hierarchical.  One ApplicationContext can have multiple child ApplicationContext and can only have one parent.   Beans in child ApplicationContext can access the beans in parent.

In SpringMVC each DispatcherServlet has one WebApplicationContext.   So there may be more than WebApplicationContext if the web application has multiple DispatcherServlet. By default Spring always look for the ApplicationContext: your_dispatcherservlet_name-servlet.xml. These DispatcherServlet related WebApplicationContext should have MVC-specific configurations.   Other non MVC-specific configuration such as the beans for service or persistence layer should be in root WebApplicationContext.

In SpringMVC the root WebApplicationContext is bootstrapped by using ContextLoadListener specified as Listener in web.xml.



<web-app>
              ............
            <context-param>
                        <param-name>contextConfigLocation</param-name>
                        <param-value>
                                    /WEB-INF/classes/META-INF/applicationContext.xml
                                    /WEB-INF/classes/META-INF/applicationSecurity.xml
                        </param-value>

            </context-param>

            <listener>
                        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
            </listener>
              ............
</web-app>


The above is the example of configuration in web.xml for root WebApplicationContext.

MVC specific WebApplicationContext is loaded for each of DispatcherServlet.  It is defined in each of servlet in web.xml. The below is an example of configuration for a DispatcherServelt where a child WebApplicationContext is specified.



<web-app>
            ...........
.
            <servlet>
                        <servlet-name>mvc-dispatcher</servlet-name>
                        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
                <init-param>
                    <param-name>contextConfigLocation</param-name>
                    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
                </init-param>
                <load-on-startup>1</load-on-startup>
            </servlet>

            ............
</web-app>