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:


(...)

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" %>





Now index.jsp should not have includes:

 

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.

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


    
    

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:


    snap
    org.springframework.web.servlet.DispatcherServlet
    2



    snap
    /*

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




    
        
            
                /WEB-INF/tiles.xml
            
        
        
    

    
        
            
                
                
            
        
        
    

    

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:

                
                    
                        
  • "> ${snap.properties['link.text']}
  • 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

    Zookeeper + Curator = Distributed sync

    An application developed for one of my recent projects at TouK involved multiple servers. There was a requirement to ensure failover for the system’s components. Since I had already a few separate components I didn’t want to add more of that, and since there already was a Zookeeper ensemble running - required by one of the services, I’ve decided to go that way with my solution.

    What is Zookeeper?

    Just a crude distributed synchronization framework. However, it implements Paxos-style algorithms (http://en.wikipedia.org/wiki/Paxos_(computer_science)) to ensure no split-brain scenarios would occur. This is quite an important feature, since I don’t have to care about that kind of problems while using this app. You just need to create an ensemble of a couple of its instances - to ensure high availability. It is basically a virtual filesystem, with files, directories and stuff. One could ask why another filesystem? Well this one is a rather special one, especially for distributed systems. The reason why creating all the locking algorithms on top of Zookeeper is easy is its Ephemeral Nodes - which are just files that exist as long as connection for them exists. After it disconnects - such file disappears.

    With such paradigms in place it’s fairly easy to create some high level algorithms for synchronization.

    Having that in place, it can safely integrate multiple services ensuring loose coupling in a distributed way.

    Zookeeper from developer’s POV

    With all the base services for Zookeeper started, it seems there is nothing else, than just connect to it and start implementing necessary algorithms. Unfortunately, the API is quite basic and offers files and directories abstractions with the addition of different node type (file types) - ephemeral and sequence. It is also possible to watch a node for changes.

    Using bare Zookeeper is hard!

    Creating connections is tedious - and there is lots of things to take care of. Handling an established connection is hard - when establishing connection to ensemble, it’s necessary to negotiate a session also. During the whole process a number of exceptions can occur - these are “recoverable” exceptions, that can be gracefully handled and not break the connection.

        class="c8"><span>So, Zookeeper API is hard.</span></p><p class="c1"><span></span></p><p class="c8"><span>Even if one is proficient with that API, then there come recipes. The reason for using Zookeeper is to be able to implement some more sophisticated algorithms on top of it. Unfortunately those aren&rsquo;t trivial and it is again quite hard to implement them without bugs.</span>
    

    And since distributed systems are hard, why would anyone want another difficult to handle tool?

    Enter Curator

    <p
        class="c8"><span>Happily, guys from Netflix implemented a nice abstraction for dealing with Zookeeper internals. They called it Curator and use it extensively in the company&rsquo;s environment. Curator offers consistent API for Zookeeper&rsquo;s functionality. It even implements a couple of recipes for distributed systems.</span>
    

    File read/write

    <p
        class="c8"><span>The basic use of Zookeeper is as a distributed configuration repository. For this scenario I only need read/write capabilities, to be able to write and read files from the Zookeeper filesystem. This code snippet writes a sample json to a file on ZK filesystem.</span>
    

    <a href="#"
                                                                                                      name="0"></a>
    
    
    EnsurePath ensurePath = new EnsurePath(markerPath);
    ensurePath.ensure(client.getZookeeperClient());
    String json = “...”;
    if (client.checkExists().forPath(statusFile(core)) != null)
         client.setData().forPath(statusFile(core), json.getBytes());
    else
         client.create().forPath(statusFile(core), json.getBytes());
    
    
    

    Distributed locking

    Having multiple systems there may be a need of using an exclusive lock for some resource, or perhaps some big system requires it’s components to synchronize based on locks. This “recipe” is an ideal match for those situations.

    ref="#"
                                                                                        name="b0329bbbf14b79ffaba1139881914aea887ef6a3"></a>
    

    
    
    lock = new InterProcessSemaphoreMutex(client, lockPath);
    lock.acquire(5, TimeUnit.MINUTES);
    … do sth …
    lock.release();
    
    
    

     (from https://github.com/zygm0nt/curator-playground/blob/master/src/main/java/pl/touk/curator/LockingRemotely.java)

    Sevice Advertisement

    <p

        class="c8"><span>This is quite an interesting use case. With many small services on different servers it is not wise to exchange ip addresses and ports between them. When some of those services may go down, while other will try to replace them - the task gets even harder. </span>
    

    That’s why, with Zookeeper in place, it can be utilised as a registry of existing services.

    If a service starts, it registers into the ServiceRegistry, offering basic information, like it’s purpose, role, address, and port.

    Services that want to use a specific kind of service request an access to some instance. This way of configuring easily decouples services from their configuration.

    Basically this scenario needs ? steps:

    <span>1. Service starts and registers its presence (</span><span class="c5"><a class="c0"
                                                                                   href="https://github.com/zygm0nt/curator-playground/blob/master/src/main/java/pl/touk/curator/WorkerAdvertiser.java#L44">https://github.com/zygm0nt/curator-playground/blob/master/src/main/java/pl/touk/curator/WorkerAdvertiser.java#L44</a></span><span>)</span><span>:</span>
    

    
    
    ServiceDiscovery discovery = getDiscovery();
                discovery.start();
                ServiceInstance si = getInstance();
                log.info(si);
                discovery.registerService(si);
    
    
    
    

    2. Another service - on another host or in another JVM on the same machine tries to discover who is implementing the service (https://github.com/zygm0nt/curator-playground/blob/master/src/main/java/pl/touk/curator/WorkerFinder.java#L50):

    <a href="#"

                                                                                                      name="3"></a>
    
    
    instances = discovery.queryForInstances(serviceName);
    
    

    The whole concept here is ridiculously simple - the service advertising its presence just stores a file with its whereabouts. The service that is looking for service providers just look into specific directory and read stored definitions.

    In my example, the structure advertised by services looks like this (+ some getters and constructor - the rest is here: https://github.com/zygm0nt/curator-playground/blob/master/src/main/java/pl/touk/model/WorkerMetadata.java):

    
    
    public final class WorkerMetadata {
        private final UUID workerId;
        private final String listenAddress;
        private final int listenPort;
    }
    
    
    

    Source code

    <p

        class="c8"><span>The above recipes are available in Curator library (</span><span class="c5"><a class="c0"
                                                                                                        href="http://curator.incubator.apache.org/">http://curator.incubator.apache.org/</a></span><span>). Recipes&rsquo;
    usage examples are in my github repo at </span><span class="c5"><a class="c0"
                                                                       href="https://github.com/zygm0nt/curator-playground">https://github.com/zygm0nt/curator-playground</a></span>
    

    Conclusion

    <p
        class="c8"><span>If you&rsquo;re in need of a reliable platform for exchanging data and managing synchronization, and you need to do it in a distributed fashion - just choose Zookeeper. Then add Curator for the ease of using it. Enjoy!</span>
    


    1. image comes from: http://www.flickr.com/photos/jfgallery/2993361148
    2. all source code fragments taken from this repo: https://github.com/zygm0nt/curator-playground

    An application developed for one of my recent projects at TouK involved multiple servers. There was a requirement to ensure failover for the system’s components. Since I had already a few separate components I didn’t want to add more of that, and since there already was a Zookeeper ensemble running - required by one of the services, I’ve decided to go that way with my solution.

    What is Zookeeper?

    Just a crude distributed synchronization framework. However, it implements Paxos-style algorithms (http://en.wikipedia.org/wiki/Paxos_(computer_science)) to ensure no split-brain scenarios would occur. This is quite an important feature, since I don’t have to care about that kind of problems while using this app. You just need to create an ensemble of a couple of its instances - to ensure high availability. It is basically a virtual filesystem, with files, directories and stuff. One could ask why another filesystem? Well this one is a rather special one, especially for distributed systems. The reason why creating all the locking algorithms on top of Zookeeper is easy is its Ephemeral Nodes - which are just files that exist as long as connection for them exists. After it disconnects - such file disappears.

    With such paradigms in place it’s fairly easy to create some high level algorithms for synchronization.

    Having that in place, it can safely integrate multiple services ensuring loose coupling in a distributed way.

    Zookeeper from developer’s POV

    With all the base services for Zookeeper started, it seems there is nothing else, than just connect to it and start implementing necessary algorithms. Unfortunately, the API is quite basic and offers files and directories abstractions with the addition of different node type (file types) - ephemeral and sequence. It is also possible to watch a node for changes.

    Using bare Zookeeper is hard!

    Creating connections is tedious - and there is lots of things to take care of. Handling an established connection is hard - when establishing connection to ensemble, it’s necessary to negotiate a session also. During the whole process a number of exceptions can occur - these are “recoverable” exceptions, that can be gracefully handled and not break the connection.

        class="c8"><span>So, Zookeeper API is hard.</span></p><p class="c1"><span></span></p><p class="c8"><span>Even if one is proficient with that API, then there come recipes. The reason for using Zookeeper is to be able to implement some more sophisticated algorithms on top of it. Unfortunately those aren&rsquo;t trivial and it is again quite hard to implement them without bugs.</span>
    

    And since distributed systems are hard, why would anyone want another difficult to handle tool?

    Enter Curator

    <p
        class="c8"><span>Happily, guys from Netflix implemented a nice abstraction for dealing with Zookeeper internals. They called it Curator and use it extensively in the company&rsquo;s environment. Curator offers consistent API for Zookeeper&rsquo;s functionality. It even implements a couple of recipes for distributed systems.</span>
    

    File read/write

    <p
        class="c8"><span>The basic use of Zookeeper is as a distributed configuration repository. For this scenario I only need read/write capabilities, to be able to write and read files from the Zookeeper filesystem. This code snippet writes a sample json to a file on ZK filesystem.</span>
    

    <a href="#"
                                                                                                      name="0"></a>
    
    
    EnsurePath ensurePath = new EnsurePath(markerPath);
    ensurePath.ensure(client.getZookeeperClient());
    String json = “...”;
    if (client.checkExists().forPath(statusFile(core)) != null)
         client.setData().forPath(statusFile(core), json.getBytes());
    else
         client.create().forPath(statusFile(core), json.getBytes());
    
    
    

    Distributed locking

    Having multiple systems there may be a need of using an exclusive lock for some resource, or perhaps some big system requires it’s components to synchronize based on locks. This “recipe” is an ideal match for those situations.

    ref="#"
                                                                                        name="b0329bbbf14b79ffaba1139881914aea887ef6a3"></a>
    

    
    
    lock = new InterProcessSemaphoreMutex(client, lockPath);
    lock.acquire(5, TimeUnit.MINUTES);
    … do sth …
    lock.release();
    
    
    

     (from https://github.com/zygm0nt/curator-playground/blob/master/src/main/java/pl/touk/curator/LockingRemotely.java)

    Sevice Advertisement

    <p

        class="c8"><span>This is quite an interesting use case. With many small services on different servers it is not wise to exchange ip addresses and ports between them. When some of those services may go down, while other will try to replace them - the task gets even harder. </span>
    

    That’s why, with Zookeeper in place, it can be utilised as a registry of existing services.

    If a service starts, it registers into the ServiceRegistry, offering basic information, like it’s purpose, role, address, and port.

    Services that want to use a specific kind of service request an access to some instance. This way of configuring easily decouples services from their configuration.

    Basically this scenario needs ? steps:

    <span>1. Service starts and registers its presence (</span><span class="c5"><a class="c0"
                                                                                   href="https://github.com/zygm0nt/curator-playground/blob/master/src/main/java/pl/touk/curator/WorkerAdvertiser.java#L44">https://github.com/zygm0nt/curator-playground/blob/master/src/main/java/pl/touk/curator/WorkerAdvertiser.java#L44</a></span><span>)</span><span>:</span>
    

    
    
    ServiceDiscovery discovery = getDiscovery();
                discovery.start();
                ServiceInstance si = getInstance();
                log.info(si);
                discovery.registerService(si);
    
    
    
    

    2. Another service - on another host or in another JVM on the same machine tries to discover who is implementing the service (https://github.com/zygm0nt/curator-playground/blob/master/src/main/java/pl/touk/curator/WorkerFinder.java#L50):

    <a href="#"

                                                                                                      name="3"></a>
    
    
    instances = discovery.queryForInstances(serviceName);
    
    

    The whole concept here is ridiculously simple - the service advertising its presence just stores a file with its whereabouts. The service that is looking for service providers just look into specific directory and read stored definitions.

    In my example, the structure advertised by services looks like this (+ some getters and constructor - the rest is here: https://github.com/zygm0nt/curator-playground/blob/master/src/main/java/pl/touk/model/WorkerMetadata.java):

    
    
    public final class WorkerMetadata {
        private final UUID workerId;
        private final String listenAddress;
        private final int listenPort;
    }
    
    
    

    Source code

    <p

        class="c8"><span>The above recipes are available in Curator library (</span><span class="c5"><a class="c0"
                                                                                                        href="http://curator.incubator.apache.org/">http://curator.incubator.apache.org/</a></span><span>). Recipes&rsquo;
    usage examples are in my github repo at </span><span class="c5"><a class="c0"
                                                                       href="https://github.com/zygm0nt/curator-playground">https://github.com/zygm0nt/curator-playground</a></span>
    

    Conclusion

    <p
        class="c8"><span>If you&rsquo;re in need of a reliable platform for exchanging data and managing synchronization, and you need to do it in a distributed fashion - just choose Zookeeper. Then add Curator for the ease of using it. Enjoy!</span>
    


    1. image comes from: http://www.flickr.com/photos/jfgallery/2993361148
    2. all source code fragments taken from this repo: https://github.com/zygm0nt/curator-playground