Virgo Snaps with Apache Tiles integration

After smoke tests become time to try using Virgo Snaps in more practical way. In modular application it will be useful to run it with templating framework. According to animal-menu-bar sample it will be better if developer of snap will not know anything about layout of host application and snippets like:

<jsp:include page="/../top.jsp"/>
(...)
<jsp:include page="/../bottom.jsp"/>

will be not necessary to put in snap pages. So lets modify a bit hosts jsps. Template page could look similar to old index.jsp:

<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>
<jsp:include page="top.jsp"/>

<tiles:insertAttribute name="body" />

<jsp:include page="bottom.jsp"/>

Now index.jsp should not have includes:

 <p>
 The Snap Menu Bar sample is intended to showcase the ability to dynamically change the content of a menu bar using snaps. Each
 of the snaps that might be displayed in the menu bar includes a top and bottom JSP page and inherits it's styling from the host
 bundle.  Therefore, the snap bundle is only responsible for showing a small subset of content.
 </p>

Template definition should have one template without any attributes (it will be added dynamicly):

<tiles-definitions>
    <definition name="defaultTemplate" template="/template.jsp">
    </definition>
</tiles-definitions>

To dynamic adding this definitions we must implement our TilesView. I’ve used one which is a part of parancoe – Open Source Java Web Framework available on Google Code: http://code.google.com/p/parancoe/source/browse/plugins/parancoe-plugin-tiles/src/main/java/org/parancoe/plugin/tiles/CheapTilesView.java?r=f42be9c3c8e2df436d4970cfdaea1aff73d9cfdb and modify it a bit for our purposes. Most interesting part is:

    protected void renderMergedOutputModel(Map model, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        try {
            super.renderMergedOutputModel(model, request, response);
        } catch (TilesException te) {
            lazyRegisterThanRender(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void lazyRegisterThanRender(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException {
        ServletContext servletContext = getServletContext();
        MutableTilesContainer container = (MutableTilesContainer)
                ServletUtil.getContainer(servletContext);;
        Definition definition = new Definition();

        String[] arr = parsePath(getUrl());
        String subContextPart = arr[0];
        String mainUrlPart    = arr[1];

        definition.setName(getUrl());
        definition.setExtends((String) getAttribute(KEY_DEFAULT_TEMPLATE,
                DEFAULT_DEFAULT_TEMPLATE));
        String attributeList = (String) getAttribute(KEY_DEFAULT_ATTRIBUTES,
                DEFAULT_DEFAULT_ATTRIBUTES);

        String[] attributes = attributeList.split(",");
        if (attributes.length == 1) {
            addAttributeWithPathValueToDefinition(attributes[0], subContextPart, mainUrlPart, definition);
        } else {
            for (String attribute : attributes) {
                addAttributeWithPathValueToDefinition(attributes[0], subContextPart, mainUrlPart + "_" + attribute, definition);
            }
        }

        container.register(definition, request, response);
        container.render(getUrl(), new Object[]{request, response});
    }

How can we see here, lazyRegisterThanRender will be invoked if Tiles will have problems in our case in resolving view name. This method registering new template which extends default one. It also adds attributes taking its values from view name. parsePath parsing path in form: view@snap or only: view:

private String[] parsePath(String path) {
        String[] arr = new String[] {"", ""};
        int indexOfAt = path.indexOf('@');
        if (indexOfAt > 0) {
            arr[0] = '/' + path.substring(indexOfAt+1, path.length());
            arr[1] = path.substring(0, indexOfAt);
        } else {
            arr[1] = path;
        }
        return arr;
    }

In our case will be only body attribute.

To use Tiles we should define tilesConfigurer in spring context. But before this we must declare DispatcherServlet in web.xml which will past requests to our controllers in web.xml:

<servlet>
    <servlet-name>snap</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>snap</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

After this simply adding WEB-INF/snap-servlet.xml context of application will be read:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd"
        default-autowire="byName">

    <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles.xml</value>
            </list>
        </property>
        <property name="useMutableTilesContainer" value="true"/>
    </bean>

    <bean id="tilesViewResolver" class="org.springframework.web.servlet.view.tiles2.TilesViewResolver">
        <property name="attributesMap">
            <map>
                <entry key="CheapTilesView.DEFAULT_TEMPLATE" value="defaultTemplate"/>
                <entry key="CheapTilesView.DEFAULT_ATTRIBUTES" value="body"/>
            </map>
        </property>
        <property name="viewClass" value="CheapTilesView"/>
    </bean>

    <bean class="MainController"/>

</beans>

After this, we must to add templates definitions: lib/tiles-jsp.tld and few entries in template.mf:

Manifest-Version: 1
Bundle-SymbolicName: animal.menu.bar
Bundle-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Multiple Styles Host
Web-ContextPath: /animal-menu-bar
Import-Library:
 org.springframework.spring;version="[3.0,3.1)"
Import-Bundle:
 com.springsource.org.apache.taglibs.standard;version="[1.1.2,1.3)",
 com.springsource.javax.servlet.jsp.jstl;version="[1.1.2, 1.1.3)",
 org.eclipse.virgo.snaps.api;version="[1.0,2.0)",
 com.springsource.org.apache.tiles;version="2.1.3",
 org.apache.tiles.core;version="2.1.3",
 org.apache.tiles.servlet;version="2.1.3",
 org.apache.tiles.jsp;version="2.1.3"
Import-Package:
 org.eclipse.virgo.snaps.core;version="[1.0,2.0)",
 javax.servlet;version="2.5",
 javax.servlet.http;version="2.5",
 javax.servlet.jsp;version="2.1",
 org.tuckey.web.filters.urlrewrite;version="[3.1.0,3.1.0]",
 org.springframework.js.resource;version="[2.0,2.1)",
 org.springframework.stereotype;version="[3.0,3.1)",
 org.springframework.web.bind.annotation;version="[3.0,3.1)",
 org.springframework.web.servlet;version="[3.0,3.1)",
 org.springframework.web.servlet.view.tiles2;version="[3.0,3.1)",
 org.apache.tiles;version="2.1.3",
 org.apache.tiles.context;version="2.1.3",
 org.apache.tiles.impl;version="2.1.3",
 org.apache.tiles.jsp.context;version="2.1.3",
 org.apache.tiles.mgmt;version="2.1.3",
 org.apache.tiles.renderer.impl;version="2.1.3",
 org.apache.tiles.servlet.context;version="2.1.3"

Our MainController will look like:

@Controller
public class MainController {
    @RequestMapping("/")
    public String rootHandler() {
        return "index";
    }
    @RequestMapping("/index.htm")
    public String snapHandler(@RequestParam("snap") String snap) {
        return "index@" + snap;
    }
}

So we must change top.jsp in host application:

                <snaps:snaps var="snaps">
                    <c:forEach var="snap" items="${snaps}">
                        <li><a href="<c:url value="index.htm?snap=${snap.properties['link.path']}"/>">
                            ${snap.properties['link.text']}</a>
                        </li>
                    </c:forEach>
                </snaps:snaps>

And also in snap.properties of both snaps link.path so it should be equals to snap subcontext (e.g. cat, dog).

After all of this we will have some troubles with resources handling so will be necessary to add urlrewrite filters like it was writed on Rob’s blog about Spring Slices – precursor of Snaps:

Our repository/usr should have:

commons-beanutils-1.8.0.jar
commons-digester-1.8.1.jar
com.springsource.org.apache.commons.collections-3.2.1.jar
com.springsource.org.apache.tiles-2.1.3.jar
com.springsource.org.tuckey.web.filters.urlrewrite-3.1.0.jar
org.eclipse.virgo.snaps.api.jar
org.eclipse.virgo.snaps.core.jar
tiles-core-2.1.3.jar
tiles-jsp-2.1.3.jar
tiles-servlet-2.1.3.jar

which we can copy from maven repository.

Patch with these changes is available on github

You May Also Like

Thought static method can’t be easy to mock, stub nor track? Wrong!

No matter why, no matter is it a good idea. Sometimes one just wants to check or it's necessary to be done. Mock a static method, woot? Impossibru!

In pure Java world it is still a struggle. But Groovy allows you to do that really simple. Well, not groovy alone, but with a great support of Spock.

Lets move on straight to the example. To catch some context we have an abstract for the example needs. A marketing project with a set of offers. One to many.

import spock.lang.Specification

class OfferFacadeSpec extends Specification {

    OfferFacade facade = new OfferFacade()

    def setup() {
        GroovyMock(Project, global: true)
    }

    def 'delegates an add offer call to the domain with proper params'() {
        given:
            Map params = [projId: projectId, name: offerName]

        when:
            Offer returnedOffer = facade.add(params)

        then:
            1 * Project.addOffer(projectId, _) >> { projId, offer -> offer }
            returnedOffer.name == params.name

        where:
            projectId | offerName
            1         | 'an Offer'
            15        | 'whasup!?'
            123       | 'doskonała oferta - kup teraz!'
    }
}
So we test a facade responsible for handling "add offer to the project" call triggered  somewhere in a GUI.
We want to ensure that static method Project.addOffer(long, Offer) will receive correct params when java.util.Map with user form input comes to the facade.add(params).
This is unit test, so how Project.addOffer() works is out of scope. Thus we want to stub it.

The most important is a GroovyMock(Project, global: true) statement.
What it does is modifing Project class to behave like a Spock's mock. 
GroovyMock() itself is a method inherited from SpecificationThe global flag is necessary to enable mocking static methods.
However when one comes to the need of mocking static method, author of Spock Framework advice to consider redesigning of implementation. It's not a bad advice, I must say.

Another important thing are assertions at then: block. First one checks an interaction, if the Project.addOffer() method was called exactly once, with a 1st argument equal to the projectId and some other param (we don't have an object instance yet to assert anything about it).
Right shit operator leads us to the stub which replaces original method implementation by such statement.
As a good stub it does nothing. The original method definition has return type Offer. The stub needs to do the same. So an offer passed as the 2nd argument is just returned.
Thanks to this we can assert about name property if it's equal with the value from params. If no return was designed the name could be checked inside the stub Closure, prefixed with an assert keyword.

Worth of  mentioning is that if you want to track interactions of original static method implementation without replacing it, then you should try using GroovySpy instead of GroovyMock.

Unfortunately static methods declared at Java object can't be treated in such ways. Though regular mocks and whole goodness of Spock can be used to test pure Java code, which is awesome anyway :)No matter why, no matter is it a good idea. Sometimes one just wants to check or it's necessary to be done. Mock a static method, woot? Impossibru!

In pure Java world it is still a struggle. But Groovy allows you to do that really simple. Well, not groovy alone, but with a great support of Spock.

Lets move on straight to the example. To catch some context we have an abstract for the example needs. A marketing project with a set of offers. One to many.

import spock.lang.Specification

class OfferFacadeSpec extends Specification {

    OfferFacade facade = new OfferFacade()

    def setup() {
        GroovyMock(Project, global: true)
    }

    def 'delegates an add offer call to the domain with proper params'() {
        given:
            Map params = [projId: projectId, name: offerName]

        when:
            Offer returnedOffer = facade.add(params)

        then:
            1 * Project.addOffer(projectId, _) >> { projId, offer -> offer }
            returnedOffer.name == params.name

        where:
            projectId | offerName
            1         | 'an Offer'
            15        | 'whasup!?'
            123       | 'doskonała oferta - kup teraz!'
    }
}
So we test a facade responsible for handling "add offer to the project" call triggered  somewhere in a GUI.
We want to ensure that static method Project.addOffer(long, Offer) will receive correct params when java.util.Map with user form input comes to the facade.add(params).
This is unit test, so how Project.addOffer() works is out of scope. Thus we want to stub it.

The most important is a GroovyMock(Project, global: true) statement.
What it does is modifing Project class to behave like a Spock's mock. 
GroovyMock() itself is a method inherited from SpecificationThe global flag is necessary to enable mocking static methods.
However when one comes to the need of mocking static method, author of Spock Framework advice to consider redesigning of implementation. It's not a bad advice, I must say.

Another important thing are assertions at then: block. First one checks an interaction, if the Project.addOffer() method was called exactly once, with a 1st argument equal to the projectId and some other param (we don't have an object instance yet to assert anything about it).
Right shit operator leads us to the stub which replaces original method implementation by such statement.
As a good stub it does nothing. The original method definition has return type Offer. The stub needs to do the same. So an offer passed as the 2nd argument is just returned.
Thanks to this we can assert about name property if it's equal with the value from params. If no return was designed the name could be checked inside the stub Closure, prefixed with an assert keyword.

Worth of  mentioning is that if you want to track interactions of original static method implementation without replacing it, then you should try using GroovySpy instead of GroovyMock.

Unfortunately static methods declared at Java object can't be treated in such ways. Though regular mocks and whole goodness of Spock can be used to test pure Java code, which is awesome anyway :)