Friday, November 25, 2011

Getting filters to play nicely with Spring

After having some struggle with getting filters to integrate well with my Spring context, I decided to write down a small tutorial for it...

To begin with, filters are defined in web.xml and are therefore not automatically part of the Spring application context, which is normally set up using the DispatcherServlet. A good way to abstract away all this is to use the DelegatingFilterProxy, which is a Spring utility class that acts as a filter, but will delegate the doFilter-method to a Spring-managed bean - normally a class extending GenericFilterBean.

As a filter is defined in web.xml and looks for the bean defined in the Spring context in applicationContext.xml, it's not really the set up that I want. Filters are part of a web application and should have access to what's usually defined in webmvc-config.xml, as part of the DispatcherServlet set up. To be able to use, e.g. request scoped beans in applicationContext.xml, you need to defined them as proxied objects in order to have them looked up at a time where the web context is available.

The small application I'll be showing here is set up with an example filter that stores a request header value into a request scoped variable which is available as a Spring bean, and can therefor be autowired in any other Spring bean later on in the execution of the request. This demonstrates a nice way to have a loose coupling between the different components, without having to e.g. pass the information in method variables. It also gives the ability to test the components outside a web context.

To begin with, a normal filter definition using the DelegatingFilterProxy needs to be added to web.xml:

    
    
        Header Filter
        org.springframework.web.filter.DelegatingFilterProxy
        
        
            targetBeanName
            headerFilter
        
    

    
        Header Filter
        /*
    


Make sure the init param "targetBeanName" is set to the name of the Spring bean to delegate to (or rely on the default, where the filter's name is used to look up the bean). Now, let's have a look at the definition of the Spring filter bean and the request scoped bean in applicationContext.xml, incl. the acutal implementation of the filter:

    
    

     
    
        
   


Note how the request scoped bean is defined to be a proxied, using
.

    package com.technowobble.web;

    import java.io.IOException;
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.filter.GenericFilterBean;

    /**
     * Intercepts all incoming requests and parses out Ninaa headers into a session scoped variable.
     */
    public class HeadersFilter extends GenericFilterBean {
        @Autowired
        private Headers headers;

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            if (request instanceof HttpServletRequest) {
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                Headers.Types[] values = Headers.Types.values();
                for (int i = 0; i < values.length; i++) {
                    headers.setHeader(values[i], httpRequest.getHeader(values[i].toString()));
                }
            }

            chain.doFilter(request, response);
        }
    }


For this set up to work and have the filter to acutually be able to look up the real object at runtime, we need to add a RequestListener to web.xml, which will wire up the request context to all beans running outsite of the DispatcherServlet, i.e. our filter.

    
    
      org.springframework.web.context.request.RequestContextListener
    


Ok - so far so good. Let's wire it up together in a controller, which uses an example component that will serve as the component that will use the information gathered from the filter. Note that the component used by the controller is not aware of any request/response objects and doesn't have any parameters in it's methods.

    package com.technowobble.controller;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import com.technowobble.component.MyComponent;

    @Controller
    @RequestMapping("/myController")
    public class MyController {
        @Autowired
        MyComponent myComponent;
        
        @ResponseBody
        @RequestMapping(method = RequestMethod.GET)
        public String createResponse() {
            return myComponent.getSomethingDependingOnHeaders();
        }
    }


The @ResponseBody is just an easy way to get rid of all view lookups and send the header values straight to the browser...

    package com.technowobble.component;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;

    import com.technowobble.web.Headers;

    @Component
    public class MyComponent {
        @Autowired
        Headers headers;
        
        public String getSomethingDependingOnHeaders() {
            return "You are accepting " + headers.getHeader(Headers.Types.Accept);
        }
    }


Now, check if everything workes as expected by launching the application using "mvn jetty:run" and browse to "http://localhost:8080/technowobble/myController/".

The last thing to report is how to test the MyComponent in a separate JUnit-test... First of all, there's no web context in a JUnit-test, and therefor no notion of a request scope. This is solved by defining a custom scope (implemented by a ThreadLocal implementation) in a separate applicationContext-test.xml which is used in the test.

  
    
      
        
          
        
      
    
  


After this, the actual test is straightforward:

    package com.technowobble.component;

    import static org.junit.Assert.assertEquals;

    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

    import com.technowobble.web.Headers;

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations="classpath*:META-INF/spring/applicationContext*.xml")
    public class MyComponentTest {
        @Autowired 
        private Headers headers;
        
        @Autowired
        private MyComponent myComponent;
        
        private static final String ACCEPT = "text/html";

        @Before
        public void setUp() throws Exception {
            headers.setHeader(Headers.Types.Accept, ACCEPT);
        }

        @Test
        public void test() {
            assertEquals(myComponent.getSomethingDependingOnHeaders(), "You are accepting " + ACCEPT);
        }
    }


Note that the headers bean is setup during the setUp()-method and that the myComponent have access to it using normal dependency injection.

That's it. The full source code can be downloaded from here

Thanks for reading!

Tuesday, September 13, 2011

A quick note on something that's been bugging me while using SpringSource STS with the GWT-plugin on my MacBook Pro...

Sometimes, when shutting down the internal devmode server I get an error dialog saying it wasn't able to shut down the process fully (even though it looks shut down in the console window).

When starting it again, it reports port 9997 to be in use already - and consequently fails to start up again. I haven't found a way to find the process within SpringSource STS, even though there are probably several ways of doing it (which I do not know about). Anyhow - I solved it using the "lsof" package (List Open Files).

To find the PID of the process using port 9997, type "lsof -i :9997" in a Terminal window. A simple "kill -9 <pid>" will take care of the rest.

I'm not sure if this happens on other platforms etc, but at least, now you know how to handle it if it hits you!

Thursday, March 3, 2011

Styling individual (and nested) tabs using GWT

I've read several forum entries trying to explain how to style GWT TabLayoutPanels, and there seems to be several ways to do it. The three most common ways are to:

1) Edit the standard.css-file and update the .gwt-TabLayoutPanel, .gwt-TabLayoutPanelTabs, .gwt-TabLayoutPanelTab, .gwt-TabLayoutPanelTabInner and .gwt-TabLayoutPanelContent.
2) Override the styles by putting your own css-file as part of html hostpage.
3) Override the styles in the ui-binder file using the @external keyword.

None of them really fit my needs... I want to be able to style indidividual tabs, including nesting tabs within tabs (with different styling). The methods above changes the globally set stylenames, and applies to all tabs being used in you application.

What I'm looking for is to style the tabs using defined styles in the ui-binder file. This way, the styles will be obfuscated and possible to apply within it's own namespace - hence only applied to individual tabs using that namespace.

Let's see an example of how I have managed to set this up. (I'm sure there are other/smarter/better ways, but looking at the forums - people aren't sharing the secrets...)

First of all, let's create the ui-binder file:

<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
 xmlns:g="urn:import:com.google.gwt.user.client.ui">

 <ui:style type="com.technowobble.client.NestedTabWidget.Style"> 
  
  .my-TabLayoutPanel {
   background-color: red !important; 
  }
  
  .myTabLayoutPanelTab {
   background-color: #DCDCDC !important;
   color: gray !important;
   -webkit-border-top-left-radius: 3px;
   -webkit-border-top-right-radius: 3px;
   -moz-border-radius-topleft: 3px;
   -moz-border-radius-topright: 3px;
   border-top-left-radius: 3px;
   border-top-right-radius: 3px;
   margin-left: 11px !important;   
  }
  
  .myTabLayoutPanelTabSelected {
   background-color: #2E8B57 !important;
   color: black !important;
  }
    
  .myTabLayoutPanelTabsContainer {
   background-color: orange;
   -moz-border-radius-topleft: 10px;
   -webkit-border-top-left-radius: 10px;
   -moz-border-radius-bottomleft: 10px;
   -webkit-border-bottom-left-radius: 10px;
   -moz-border-radius-topright: 10px;
   -webkit-border-top-right-radius: 10px;
   -moz-border-radius-bottomright: 10px;
   -webkit-border-bottom-right-radius: 10px;
  } 
  
  .myTabLayoutPanelContent {
   border-color: #2E8B57 !important;
  }   
  
  .myNestedTabLayoutPanel {
   background-color: lime !important; 
  }
  
  .myNestedTabLayoutPanelTab {
   background-color: black !important;
   color: gray !important;
   -webkit-border-top-left-radius: 3px;
   -webkit-border-top-right-radius: 3px;
   -moz-border-radius-topleft: 3px;
   -moz-border-radius-topright: 3px;
   border-top-left-radius: 3px;
   border-top-right-radius: 3px;
   margin-left: 11px !important;
  }
 
  .myNestedTabLayoutPanelTabSelected {
   background-color: #7B68EE !important;
   color: black !important;
  }
  
  .myNestedTabLayoutPanelContent {
   border-color: #7B68EE !important;
   background-color: fuchsia !important;
   color: white;
  }  
 </ui:style>

 <g:TabLayoutPanel ui:field="tabLayoutPanel" barHeight="2" barUnit="EM" width="400px" height="150px" addStyleNames="{style.my-TabLayoutPanel}">
  <g:tab>
   <g:header>Tab 1</g:header>
   <g:TabLayoutPanel barHeight="2" barUnit="EM">
    <g:tab>
     <g:header>Nested tab 1.1</g:header>
     <g:HTML wordWrap="true">Nested tab 1.1 content</g:HTML>
    </g:tab>
    <g:tab>
     <g:header>Nested tab 1.2</g:header>
     <g:HTML wordWrap="true">Nested tab 1.2 content</g:HTML>
    </g:tab>
   </g:TabLayoutPanel>
  </g:tab>
  <g:tab>
   <g:header>Tab 2</g:header>
   <g:TabLayoutPanel barHeight="2" barUnit="EM">
    <g:tab>
     <g:header>Nested tab 2.1</g:header>
     <g:HTML wordWrap="true">Nested tab 2.1 content</g:HTML>
    </g:tab>
    <g:tab>
     <g:header>Nested tab 2.2</g:header>
     <g:HTML wordWrap="true">Nested tab 2.2 content</g:HTML>
    </g:tab>
    <g:tab>
     <g:header>Nested tab 2.3</g:header>
     <g:HTML wordWrap="true">Nested tab 2.3 content</g:HTML>
    </g:tab>    
   </g:TabLayoutPanel>
  </g:tab>
 </g:TabLayoutPanel>
</ui:UiBinder> 

This file defines a tab panel with two tabs, each of which have a separate tab panel as it's content. The specified style tags pretty much mimics the "standard" style names for a TabLayoutPanel and I've named them thereafter. Remember, they could be named whatever as they will be obfuscated anyway.

The only style that is actually applied directly in the ui-binder file is the .my-TabLayoutPanel, which could just as well have had applied at run-time instead.

Now, let's create the corresponding Java-class, which will style the defined tabs using the above styles:

package com.technowobble.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.Widget;

public class NestedTabWidget extends Composite {

 private static NestedTabWidgetUiBinder uiBinder = GWT
   .create(NestedTabWidgetUiBinder.class);

 interface NestedTabWidgetUiBinder extends UiBinder<Widget, NestedTabWidget> {
 }
 
 interface Style extends CssResource {
  // Tab container (containing the .gwt-TabLayoutPanelTabs styling
  String myTabLayoutPanelTabsContainer();
  // General tab styling
  String myTabLayoutPanelTab();
  // Specific styling for selected tab
  String myTabLayoutPanelTabSelected();
  // Applied to tab content
  String myTabLayoutPanelContent();
  // Applied to entire nested tab panel
  String myNestedTabLayoutPanel();
  // General inner tab styling
  String myNestedTabLayoutPanelTab();
  // Specific styling for selected inner tab
  String myNestedTabLayoutPanelTabSelected();
  // Applied to inner tab content
  String myNestedTabLayoutPanelContent();
 }
 
 @UiField 
 Style style;
 
 @UiField
 TabLayoutPanel tabLayoutPanel;

 public NestedTabWidget() {
  initWidget(uiBinder.createAndBindUi(this));
  
  // style the tab container (gray bar)
  ((Element) tabLayoutPanel.getElement().getChild(1)).addClassName(style.myTabLayoutPanelTabsContainer());
  // style the tabs
  styleTabPanel(tabLayoutPanel, style.myTabLayoutPanelTab(), style.myTabLayoutPanelTabSelected(), style.myTabLayoutPanelContent());
  
  // style all inner tabs (in uibinder)
  for (int i = 0; i < tabLayoutPanel.getWidgetCount(); i++) {
   Widget widget = tabLayoutPanel.getWidget(i);
   
   // add content style no matter what the content is
   widget.addStyleName(style.myTabLayoutPanelContent());
   
   if (widget instanceof TabLayoutPanel) {
    final TabLayoutPanel nestedTabLayoutPanel = (TabLayoutPanel) widget;
    // style inner tabLayoutPanel  
    nestedTabLayoutPanel.addStyleName(style.myNestedTabLayoutPanel());
    styleTabPanel(nestedTabLayoutPanel, style.myNestedTabLayoutPanelTab(), style.myNestedTabLayoutPanelTabSelected(), style.myNestedTabLayoutPanelContent());

    // re-style on selects
    nestedTabLayoutPanel.addSelectionHandler(new SelectionHandler<Integer>() {     
     @Override
     public void onSelection(SelectionEvent<Integer> event) {
      styleTabPanel(nestedTabLayoutPanel, style.myNestedTabLayoutPanelTab(), style.myNestedTabLayoutPanelTabSelected(), style.myNestedTabLayoutPanelContent());      
     }
    });       
   }
  }
 }
 
 @UiHandler("tabLayoutPanel")
 public void onTabSelect(SelectionEvent<Integer> event) {
  styleTabPanel(tabLayoutPanel, style.myTabLayoutPanelTab(), style.myTabLayoutPanelTabSelected(), style.myTabLayoutPanelContent());
 } 
  
 private void styleTabPanel(TabLayoutPanel tabPanel, String style, String styleSeleced, String styleContent) {
  for (int i = 0; i < tabPanel.getWidgetCount(); i++) {
   Widget tab = tabPanel.getTabWidget(i);
   
   // style the actual tab
   tab.getParent().addStyleName(style);
   if (i == tabPanel.getSelectedIndex()) {
    tab.getParent().addStyleName(styleSeleced);
   } else {
    tab.getParent().removeStyleName(styleSeleced);
   }
   
   // style the added content
   Widget content = tabPanel.getWidget(i);
   content.addStyleName(styleContent);
  } 
 }
}

You can see what the different styles are used for in the comments (according to the JavaDoc of the TabLayoutPanel) - the only interesting thing to note is that I've added styling to the div-tag containing the .gwt-TabLayoutPanelTabs div, in order to style the background behind the tabs.

When initializing the widget I style all the tabs once, but as I can't use addStyleDependantName() to style select/unselect I also have to apply these styles on every select/unselect. This is applied to both the outer TabLayoutPanels, as the inner TabLayoutPanels. The reason the addStyleDependantName() can't be used is because the names are obfuscated, and adding a "-select" to it doesn't match the name of the non-obfuscated corresponding selected style in the ui-binder file. There are surely a better way of doing this, and I'd be happy to hear if you have any suggestions here...

I haven't put up any running example of this, but you can download the source code as an Eclipse-project here and try for yourself. I apologize for the color-schema I've used in the example - looks like a 5-year old gone crazy, but it fills the purpose of showing where each style gets applied...

Have fun!