Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Sunday, January 19, 2014

Mocking a Filter in Spring

No comments:

Spring has provided the org.springframework.mock package for mocking various things in Spring. This is the unit test code that will mock the filter.



package com.test;
import java.io.IOException;
import java.io.StringReader;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
public class ErrorHandlerMockTest {
        @Test
        public void testDoFilter() throws ServletException, IOException {
                MockHttpServletRequest request = new MockHttpServletRequest();
                MockHttpServletResponse response = new MockHttpServletResponse();
                MockFilterConfig config = new MockFilterConfig();
                
                FilterChain filterChain = new MockFilterChain() {
                        @Override
                        public void doFilter(ServletRequest req, ServletResponse res) {
                                throw new NullPointerException("test Filter");
                        }
                };
                
                ErrorHandler filter = new ErrorHandler();
                filter.init(config);
                filter.doFilter(request, response, filterChain);
                
                String contentAsString = response.getContentAsString();
                ObjectMapper mapper = new ObjectMapper();
                mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// ResponseInfo object is the custom object which will be returned as json response in filters
                ResponseInfo responseInfo = mapper.readValue(new StringReader(contentAsString), ResponseInfo.class);
                String errorCode = responseInfo.getResponseCode();
                Assert.assertEquals("ERR_CODE_000000", errorCode);
        }
}
Happy Coding!
Read More

Filters to handle errors in application

No comments:
I am having a spring web service application. I want to handle all the errors in that application and I want to return json with those errors.



This will not block client from expecting the response from the server. Somehow the server will return some json data with data or with error/exception.

Client can handle accordingly.

1) Add the filter in your web.xml file
    <filter>
         <filter-name>errorHandler</filter-name>
         <filter-class>com.test.ErrorHandler</filter-class>
    </filter>
    <filter-mapping>
         <filter-name>errorHandler</filter-name>
         <url-pattern>*</url-pattern>
    </filter-mapping>

2)  This is the class file of our ErrorHandler Filter

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletResponse;



import org.apache.log4j.Logger;

import org.codehaus.jackson.map.ObjectMapper;



// my exception class

import com.test.exception.CustomException;



public class ErrorHandler implements Filter {



        private static final String UTF_8 = "UTF-8";

        private static final String APPLICATION_JSON = "application/json";

        private static final Logger S_LOGGER= Logger.getLogger(ErrorHandler.class);

        private static boolean isDebugEnabled = S_LOGGER.isDebugEnabled();

        

        @Override

        public void init(FilterConfig filterConfig) throws ServletException {

        }



        @Override

        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

                try {

                        chain.doFilter(request, response);

                } catch (Exception e) {

                        if (isDebugEnabled) {

                                S_LOGGER.debug("Entering into the catch of ErrorHandler.doFilter()");

                        }

                        CustomException customException = new CustomException(e);

                        

                        ResponseInfo<Object> responseData = new ResponseInfo<Object>();

                        // Here construct the final response object - This is the custome method to construct a java object which will be a response

                        ResponseInfo<Object> finalOuptut = responseDataConstruct(responseData, customException, RESPONSE_STATUS_ERROR, ERR_CODE_000000);

                        

                        ObjectMapper mapper = new ObjectMapper();

                        // Convert it as Strng to return

                        String objectToReturn = mapper.writeValueAsString(finalOuptut);

                        

                        // It returns the json with data or error

                        HttpServletResponse res = (HttpServletResponse)response;

                        res.setStatus(res.SC_OK);

                        

                        response.setContentType(APPLICATION_JSON);

                        response.setCharacterEncoding(UTF_8);

                        PrintWriter out = response.getWriter();

                        out.print(objectToReturn);

                        out.flush();

                }

        }



        @Override

        public void destroy() {

        }

}

Thats it.

Normal Flow :

Whenever a error occurs(E.g NullPointerException) in a webapplication. Webpage will be displayed with that error plain. If it is webservice application, that error page will be returned as response.

Interceptors :
When ever a error occurs in application logic, response will come through the intereceptors.
We are adding our custom interceptor and If there is any error occurred we will return response(JSON) with that error. Client will handle accordingly.blog

--
Thank you.

Regards,
Kaleeswaran S
Read More