Skip to main content

Extending Tuckey URL Rewrite Filter with Tridion-published rules

This post shows a way of extending Paul Tuckey’s URL rewrite filter (https://code.google.com/p/urlrewritefilter/). Namely, it extends the Java version 4.0.3 of the filter and makes it use rewrite/redirect rules published from Tridion.

The rules are published to the Content Delivery Database as a dynamic DD4T page, and use specific view model objects that make reading the rules very easy. The extension I wrote will also attempt to load the existing rules in file “/WEB-INF/urlrewrite.xml” - the default configuration file used by URL rewrite filter.

Tridion Part

We define an Embedded Schema called EmbeddedRedirect having the following fields:
  • from - single value text;
  • to - single value text;
  • permanent - singe value drop down or radian button text field based on values of a list with possible values “Yes” or “No”;

We define a Schema called Redirects having the following field:
  • redirect - multi value embedded field based on Schema EmbeddedRedirect;

Next, we also create a Component on Schema Redirects and create several values for the actual from/to redirects. For example:
  • from = ^/maps/?$
  • to = /services/maps/
  • permanent = Yes

The rule above will match using regular expressions the URL path “/maps” followed by a slash or not and will perform a permanent redirect (using status code 301) to the same host, but for path “/services/maps/“.

Finally we create a Page using a DD4T PT and put the Redirects Component on it (using a DD4T standard CT), and we publish the page.

DD4T Part

This implementation being a DD4T solution, we define specific view models for the EmbeddedRedirect and Redirects Schemas.

EmbeddedRedirect.java:

@TridionModel(rootElementName = "embeddedRedirect")
public class EmbeddedRedirect extends BaseModel {

    @TridionField
    private String from;

    @TridionField
    private String to;

    @TridionField
    private String permanent;

    private boolean isPermanent;

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public boolean isPermanent() {
        return isPermanent;
    }

    public void setPermanent(String permanent) {
        this.permanent = permanent;
        isPermanent = "Yes".equals(permanent);
    }
}

Redirects.java:

@TridionModel(rootElementName = "redirects")
public class Redirects extends BaseModel {

    @TridionField(fieldName = "redirect", fieldType = TridionFieldType.Embedded)
    private List<EmbeddedRedirect> redirects;

    public List<EmbeddedRedirect> getRedirects() {
        return redirects;
    }

    public void setRedirects(List<EmbeddedRedirect> redirects) {
        this.redirects = redirects;
    }
}

The URL Rewrite Filter Extension

We start by extending the original filter org.tuckey.web.filters.urlrewrite.UrlRewriteFilter

public class DynamicConfUrlRewriteFilter extends UrlRewriteFilter {

First, we override the filter’s init() method and make it load a filter init parameter called “confUrl” that is defined in file web.xml. This URL indicates the path of the Tridion page that contains the rewrite/redirect rules.

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        super.init(filterConfig);
        confUrl = filterConfig.getInitParameter("confUrl");
        if (StringUtils.isEmpty(confUrl)) {
            throw new ServletException("Filter init parameter 'confUrl' cannot be empty. Check your web.xml.");
        }
    }

Next, we get to implement the actual extension of the original URL rewrite filter — method getUrlRewriter(), which returns a org.tuckey.web.filters.urlrewrite.UrlRewriter object used internally by the filter to perform matches and redirects/rewrites on each request. In a real implementation, we cache the UrlRewriter and only load a new one when it either falls off the cache, or if it gets expired by a new publish of the Redirects page. In this post, a simplified version of the method is shown below:

    @Override
    protected UrlRewriter getUrlRewriter(ServletRequest request, ServletResponse response, FilterChain chain) {
        String url = resolveRewriteUrl();
        GenericPage page = getUrlRewritePage(url);
        return load(page);
    }

The method resolveRewriteUrl() uses a PublicationResolver to determine the URL of the Redirects page in the current Publication.

Method getUrlRewritePage uses DD4T’s PageFactory to load the Page model of the Redirects page.

Finally, the load(page) method performs the actual parsing logic that reads each EmbeddedRedirect on the page and creates a org.tuckey.web.filters.urlrewrite.Conf object that is then used to create the UrlRewriter object:

    private UrlRewriter load(GenericPage page) {
        UrlRewriter result = null;

        String urlRewriteXml = getUrlRewriteXml(page);
        InputStream inputStream = new ByteArrayInputStream(urlRewriteXml.getBytes());
        Conf conf = new Conf(inputStream, page.getId());

        if (conf.isOk() && conf.isEngineEnabled()) {
            result = new UrlRewriter(conf);
        }

        return result;
    }

The Configuration Part

The web.xml descriptor contains the definition of the filter, its initial parameter configuration and the filter mappings:

    <filter>
        <filter-name>UrlRewriteFilter</filter-name>
        <filter-class>com.my.web.filters.DynamicConfUrlRewriteFilter</filter-class>
        <init-param>
            <param-name>confPath</param-name>
            <param-value>/WEB-INF/urlrewrite.xml</param-value>
        </init-param>
        <init-param>
            <param-name>confUrl</param-name>
            <param-value>/system/urlrewrite.html</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>UrlRewriteFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>


All it’s left now is to add the redirect rules in the Redirects Component. Happy redirecting! :)


Comments

Popular posts from this blog

Toolkit - Dynamic Content Queries

This post if part of a series about the  File System Toolkit  - a custom content delivery API for SDL Tridion. This post presents the Dynamic Content Query capability. The requirements for the Toolkit API are that it should be able to provide CustomMeta queries, pagination, and sorting -- all on the file system, without the use third party tools (database, search engines, indexers, etc). Therefore I had to implement a simple database engine and indexer -- which is described in more detail in post Writing My Own Database Engine . The querying logic does not make use of cache. This means the query logic is executed every time. When models are requested, the models are however retrieved using the ModelFactory and those are cached. Query Class This is the main class for dynamic content queries. It is the entry point into the execution logic of a query. The class takes as parameter a Criterion (presented below) which triggers the execution of query in all sub-criteria of a Criterio

A DD4T.net Implementation - Custom Binary Publisher

The default way to publish binaries in DD4T is implemented in class DD4T.Templates.Base.Utils.BinaryPublisher and uses method RenderedItem.AddBinary(Component) . This produces binaries that have their TCM URI as suffix in their filename. In my recent project, we had a requirement that binary file names should be clean (without the TCM URI suffix). Therefore, it was time to modify the way DD4T was publishing binaries. The method in charge with publishing binaries is called PublishItem and is defined in class BinaryPublisher . I therefore extended the BinaryPublisher and overrode method PublishItem. public class CustomBinaryPublisher : BinaryPublisher { private Template currentTemplate; private TcmUri structureGroupUri; In its simplest form, method PublishItem just takes the item and passes it to the AddBinary. In order to accomplish the requirement, we must specify a filename while publishing. This is the file name part of the binary path of Component.BinaryConten

Scaling Policies

This post is part of a bigger topic Autoscaling Publishers in AWS . In a previous post we talked about the Auto Scaling Groups , but we didn't go into details on the Scaling Policies. This is the purpose of this blog post. As defined earlier, the Scaling Policies define the rules according to which the group size is increased or decreased. These rules are based on instance metrics (e.g. CPU), CloudWatch custom metrics, or even CloudWatch alarms and their states and values. We defined a Scaling Policy with Steps, called 'increase_group_size', which is triggered first by the CloudWatch Alarm 'Publish_Alarm' defined earlier. Also depending on the size of the monitored CloudWatch custom metric 'Waiting for Publish', the Scaling Policy with Steps can add a difference number of instances to the group. The scaling policy sets the number of instances in group to 1 if there are between 1000 and 2000 items Waiting for Publish in the queue. It also sets the