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

Content Delivery Monitoring in AWS with CloudWatch

This post describes a way of monitoring a Tridion 9 combined Deployer by sending the health checks into a custom metric in CloudWatch in AWS. The same approach can also be used for other Content Delivery services. Once the metric is available in CloudWatch, we can create alarms in case the service errors out or becomes unresponsive. The overall architecture is as follows: Content Delivery service sends heartbeat (or exposes HTTP endpoint) for monitoring Monitoring Agent checks heartbeat (or HTTP health check) regularly and stores health state AWS lambda function: runs regularly reads the health state from Monitoring Agent pushes custom metrics into CloudWatch I am running the Deployer ( installation docs ) and Monitoring Agent ( installation docs ) on a t2.medium EC2 instance running CentOS on which I also installed the Systems Manager Agent (SSM Agent) ( installation docs ). In my case I have a combined Deployer that I want to monitor. This consists of an Endpoint and a

Debugging a Tridion 2011 Event System

OK, so you wrote your Tridion Event System. Now it's time to debug it. I know this is a hypothetical situtation -- your code never needs any kind of debugging ;) but indulge me... Recently, Alvin Reyes ( @nivlong ) blogged about being difficult to know how exactly to debug a Tridion Event System. More exactly, the question was " What process do I attach to for debugging even system code? ". Unfortunately, there is no simple or generic answer for it. Different events are fired by different Tridion CM modules. These modules run as different programs (or services) or run inside other programs (e.g. IIS). This means that you will need to monitor (or debug) different processes, based on which events your code handles. So the usual suspects are: dllhost.exe (or dllhost3g.exe ) - running as the MTSUser is the SDL Tridion Content Manager COM+ application and it fires events on generic TOM objects (e.g. events based on Tridion.ContentManager.Extensibility.Events.CrudEven