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

Running sp_updatestats on AWS RDS database

Part of the maintenance tasks that I perform on a MSSQL Content Manager database is to run stored procedure sp_updatestats . exec sp_updatestats However, that is not supported on an AWS RDS instance. The error message below indicates that only the sa  account can perform this: Msg 15247 , Level 16 , State 1 , Procedure sp_updatestats, Line 15 [Batch Start Line 0 ] User does not have permission to perform this action. Instead there are several posts that suggest using UPDATE STATISTICS instead: https://dba.stackexchange.com/questions/145982/sp-updatestats-vs-update-statistics I stumbled upon the following post from 2008 (!!!), https://social.msdn.microsoft.com/Forums/sqlserver/en-US/186e3db0-fe37-4c31-b017-8e7c24d19697/spupdatestats-fails-to-run-with-permission-error-under-dbopriveleged-user , which describes a way to wrap the call to sp_updatestats and execute it under a different user: create procedure dbo.sp_updstats with execute as 'dbo' as

I Have Gone Dark

Maybe it's the Holidays, but my mood has gone pretty dark. That is, regarding the look and feel of my computer and Tridion CME, of course. What I did was to dim the lights on the operating system, so I installed Placebo themes for Windows 7 . I went for the Ashtray look -- great name :) My VM looks now like this: But, once you change the theme on Windows, you should 'match' the theme of your applications. Some skin easily, some not. The Office suite has an in-built scheme, which can be set to Black , but it doesn't actually dim the ribbon tool bars -- it looks quite weird. Yahoo Messenger is skinnable, but you can't change the big white panels where you actually 'chat'. Skype is not skinnable at all. For Chrome, there are plenty of grey themes. Now i'm using Pro Grey . But then I got into changing the theme of websites. While very few offer skinnable interfaces (as GMail does), I had to find a way to darken the websites... Enter Stylish -- a pl

REL Standard Tag Library

The RSTL is a library of REL tags providing standard functionality such as iterating collections, conditionals, imports, assignments, XML XSLT transformations, formatting dates, etc. RSTL distributable is available on my Google Code page under  REL Standard Tag Library . Always use the latest JAR . This post describes each RSTL tag in the library explaining its functionality, attributes and providing examples. For understanding the way expressions are evaluated, please read my post about the  Expression Language used by REL Standard Tag Library . <c:choose> / <c:when> / <c:otherwise> Syntax:     <c:choose>         <c:when test="expr1">             Do something         </c:when>         <c:when test="expr2">             Do something else         </c:when>         <c:otherwise>             Do something otherwise         </c:otherwise>     </c:choose> Att