Skip to main content

OData Page Provider for DD4T Java

This little project has been on my mind for a while now: write a set of DD4T providers for OData (aka the Content Delivery Web Service). The approach is to remove all mentions of the CD API from the DD4T application itself and restrict Tridion interaction to the OData service. The DD4T application would use an OData client to talk with the service.

Since communication with OData goes over HTTP, the number of queries to the service must be kept to a minimum, so the DD4T PageFactory will make heavy use of caching. I implemented an EHCache provider for DD4T, but that's not the scope of this blog post.

So finally, this weekend I set on to writing these providers. The first challenge quickly showed up; the CD API is used in many DD4T classes and in the cases where the actual functionality is not used directly, DD4T still makes extensive use of CD API classes and interfaces.

It took me a couple of hours to remove the mentions to com.tridion.* packages. During this process, the provider interfaces (in package org.dd4t.providers of project dd4t-api) changed a bit, because the original interfaces returned Tridion objects. The Page provider I am going to focus on in this post changed to the following:

public interface PageProvider {
    public String getPageContentByURL(String url, int publication)
            throws ItemNotFoundException, SerializationException;

    public String getPageContentById(int id, int publication)
            throws ItemNotFoundException, SerializationException;
}

In the latest version of DD4T (currently not released yet), the DD4T templates can produce XML or JSON in plain or compressed format. Compression is for example GZip, then Base64 to bring it back to a ASCII encoding. This can all be configured in the Template Building Blocks. For this implementation, I am going to use JSON without compression.

The implementing Page provider goes something like this:

public String getPageContentByURL(String url, int publication)
            throws ItemNotFoundException, SerializationException {
    String filter = String.format("PublicationId eq %d and Url eq '%s'", publication, url);
    OEntity pageEntity = ODataClient.INSTANCE.getPageEntities().filter(filter).
            expand("PageContent").execute().firstOrNull();

    if (pageEntity == null) {
        throw new ItemNotFoundException();
    }

    OEntity pageContentEntity = pageEntity.getLink("PageContent", OLink.class).
            getRelatedEntity();
    if (pageContentEntity == null) {
        throw new ItemNotFoundException();
    }

    return pageContentEntity.getProperty("Content", String.class).getValue();
}

The implementation makes use of the OData4J client. I had a previous encounter with this one, and I had to patch it in order to make it work with the non-standard Date format the Tridion CD WS is using. Make sure to use my patched version.

The OData4J client code is rather straight forward: get the singleton client (more about it below), filter the Pages collection to retrieve only from the given Publication and only the item with the given URL, then expand the PageContent related entity, because that's the one that contains the actual serialized DD4T Page model.

The OData client is actually of type org.odata4j.consumer.ODataConsumer and this is the one that handles the communication with the CD Web Services. The singleton ODataClient I have defined in package org.dd4t.providers.impl looks like this:

public enum ODataClient {
    INSTANCE;
    public static final String CONFIG_FILENAME = "odata.properties";

    private final Logger LOG = LoggerFactory.getLogger(ODataClient.class);
    private final ODataConsumer client;
    private final OQueryRequest<OEntity> pageEntities;

    private ODataClient() {
        String odataURL = "MISSING_" + CONFIG_FILENAME + "_";
        try {
            InputStream input = ODataClient.class.getClassLoader().
                    getResourceAsStream(CONFIG_FILENAME);
            if (input == null) {
                throw new IOException("Cannot find properties file '" + CONFIG_FILENAME +
                        "' in classpath");
            }

            Properties properties = new Properties();
            properties.load(input);

            odataURL = properties.getProperty("BaseURL");
        } catch (IOException ioe) {
            LOG.error("Cannot load OData properties file", ioe);
        }

        client = ODataConsumers.create(odataURL);
        pageEntities = client.getEntities("Pages");
    }

    public OQueryRequest<OEntity> getPageEntities() {
        return pageEntities;
    }
}

The 'singleton' client piggy backs on the Java enum quirk, which guarantees there is at all times one and only one instance of the 'singleton'. The initialization code expects a file called odata.properties to be available in the application classpath. It reads the CD WebService baseURL from this properties file (e.g. http://localhost:8080/odata.svc) and it instantiates the ODataConsumer client then. Finally, the utility getter returns a OQueryRequest object ready to be used against the OData service.

Finally, the DD4T PageFactory implementation class in package org.dd4t.factories.impl is pretty standard and makes use of a Cache provider and a Page provider. The findPageByUrl method is shown below as indication (I have not really modified this method except for the signature of the pageProvider.getPageContentByURL method):

public GenericPage findPageByUrl(String url, int publicationId, RequestContext context) throws ItemNotFoundException, FilterException, ParseException, SerializationException {
    String cacheKey = publicationId + "-" + url;
    GenericPage page = (GenericPage) getCacheProvider().loadFromLocalCache(cacheKey);
    if (page == null) {
        String pageSource = pageProvider.getPageContentByURL(url, publicationId);
        if (pageSource == null || pageSource.length() == 0) {
            throw new ItemNotFoundException();
        }
        page = getPageFromSource(pageSource);
        doFilters(page, context, BaseFilter.RunPhase.BeforeCaching);
        getCacheProvider().storeInItemCache(cacheKey, page, publicationId);
    }

    doFilters(page, context, BaseFilter.RunPhase.AfterCaching);
    return page;
}

Where the getPageFromSource method is simply calling the deserialization of the String to actual Page DD4T object model.

That's all folks... sweet and short :)

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

SDL Web 8 - Content Delivery Microservices

Among the new features in SDL Web 8 there are the Content Delivery Microservices, namely: Audience Manager Content Deployer Contextual Image Delivery Discovery Service Dynamic Content Dynamic Linking Profiling and Personalization Metadata Query Taxonomy User Generated Content These microservices make up the Content Interaction Services and they expose the existing Content Delivery in-process APIs as RESTful services. They provide the server-side component in a Services-Oriented Architecture and act as data layer between the the web client and the Content Delivery Storage Layer. According to the SDL marketing, these microservices: Simplify upgrades, thus offering shorter time to value Modernize architecture, offering better separation between the web application and Tridion APIs Offer more flexibility with less downtime and improved scalability Improve quality, being self-running, contained and having less dependencies In technical words, these microservices