Skip to main content

Toolkit - Dynamic Query Sorting and Pagination

This post if part of a series about the File System Toolkit - a custom content delivery API for SDL Tridion.

In the previous post Dynamic Content Queries, I presented a Query class that performs CustomMeta queries on JSON models published to the file system. This post presents the logic that sorts and paginates the result set.

The Query class defines four members that help the pagination and sorting logic:
  • Sorter -- the Comparator that perform the actual sorting of two ItemMeta objects (it returns an order between two ItemMeta instances);
  • page -- the page index to return out of all pages;
  • pageSize -- the number of items on a page;
  • totalItemCount -- the total number of items before pagination was applied;

Sorting

Sorting can be specified on different columns and can use different directions for each column (ascending, descending). A sort column is a predefined metadata of a model (title, last publish date) or a CustomMeta. An association between a sort column and sort direction is called a sort term. There can be several sort terms associated with a Query object.

Sorting is applied starting with each the first sort term. For items that are considered equal, the next sort term is applied to identify an order; the sorting logic continues until an order is established between two ItemMetas or when we run out of sort terms.

SortColumn

SortColumn class is an enum that defines what can we sort on:

public enum SortColumn {
    CUSTOM_META, LAST_MODIFIED, LAST_PUBLISH, TITLE
}

SortDirection

SortDirection class is an enum that defines the direction of sorting for a given column:

public enum SortDirection {
    ASCENDING, DESCENDING
}

SortTerm

This class is an association between a SortColumn enum, a SortDirection enum and potentially a String representing the CustomMeta name.

Sorter

This class implements the Comparator interface and it is a comparator of ItemMeta objects (i.e. ComponentMeta or PageMeta). The class holds a list of SortTerm object, which are applied in order when determining the order between two ItemMeta objects.

public int compare(ItemMeta i1, ItemMeta i2) {
    for (SortTerm sortTerm : sortTerms) {
        int compare = compare(i1, i2, sortTerm);
        if (compare != 0) {
            return compare;
        }
    }

    return 0;
}

The specialized method compare(ItemMeta, ItemMeta, SortTerm) determines the order between the two ItemMeta objects according to the specified SortTerm:

private int compare(ItemMeta i1, ItemMeta i2, SortTerm sortTerm) {
    SortColumn column = sortTerm.getColumn();
    SortDirection direction = sortTerm.getDirection();

    switch (column) {
        case CUSTOM_META:
            String customMeta = sortTerm.getCustomMeta();
            CustomMetaItem customMetaItem1 = getCustomMetaItem(i1, customMeta);
            CustomMetaItem customMetaItem2 = getCustomMetaItem(i2, customMeta);
            return compare(customMetaItem1, customMetaItem2, direction);

        case LAST_MODIFIED:
            Date date1 = getLastModified(i1);
            Date date2 = getLastModified(i2);
            return direction == SortDirection.ASCENDING ?
                date1.compareTo(date2) : date2.compareTo(date1);

        case LAST_PUBLISH:
            date1 = getLastPublished(i1);
            date2 = getLastPublished(i2);
            return direction == SortDirection.ASCENDING ?
                date1.compareTo(date2) : date2.compareTo(date1);

        case TITLE:
            String title1 = getTitle(i1);
            String title2 = getTitle(i2);
            return direction == SortDirection.ASCENDING ?
                title1.compareTo(title2) : title2.compareTo(title1);

        default:
            log.error("Unknown sort column {}", column);
    }

    return 0;
}

A couple of the helper method are presented below, such as getCustomMetaItem and compare(CustomMeta, CustomMeta, SortDirection). The goal in these method is to provide empty values instead of null such as the comparison can be performed correctly even for missing values.

private CustomMetaItem getCustomMetaItem(ItemMeta itemMeta, String key) {
    if (itemMeta == null) {
        return null;
    }

    CustomMeta customMeta = itemMeta.getCustomMeta();
    if (customMeta == null) {
        return null;
    }

    CustomMetaItem customMetaItem = customMeta.getByName(key);
    if (customMetaItem == null) {
        return null;
    }

    return customMetaItem;
}

private int compare(CustomMetaItem meta1, CustomMetaItem meta2, SortDirection direction) {
    if (meta1 == null && meta2 == null) {
        return 0;
    } else if (meta1 == null) {
        return direction == SortDirection.ASCENDING ? -1 : 1;
    } else if (meta2 == null) {
        return direction == SortDirection.ASCENDING ? 1 : -1;
    }

    CustomMetaType type1 = meta1.getType();
    CustomMetaType type2 = meta2.getType();
    if (type1 != type2) {
        log.warn("Cannot compare custom meta {} with {}", type1, type2);
        return 1;
    }

    switch (type1) {
        case DATE:
            Date date1 = meta1.getDateValue();
            date1 = date1 == null ? MIN_DATE : date1;
            Date date2 = meta2.getDateValue();
            date2 = date2 == null ? MIN_DATE : date2;
            return direction == SortDirection.ASCENDING ?
                date1.compareTo(date2) : date2.compareTo(date1);

        case NUMERIC:
            float float1 = meta1.getNumericValue();
            float float2 = meta2.getNumericValue();
            if (float1 == float2) {
                return 0;
            } else if (float1 < float2) {
                return direction == SortDirection.ASCENDING ? -1 : 1;
            } else {
                return direction == SortDirection.ASCENDING ? 1 : -1;
            }

        case STRING:
            String string1 = join(meta1.getStringValues());
            String string2 = join(meta2.getStringValues());
            return direction == SortDirection.ASCENDING ?
                string1.compareTo(string2) : string2.compareTo(string1);
    }

    return 0;
}

Paginating

Once sorting is done, the results can be paginated. The routine below is a simple pagination logic that retains the indexes of a given 'page' out of the list of all items.

private <T> List<T> applyPagination(List<T> items) {
    if (page == 0 && pageSize == 0) {
        return items;
    }

    int offset = page <= 1 || pageSize <= 0 ? 0 : Math.min(items.size(), (page - 1) * pageSize);
    int limit = pageSize <= 0 ? 0 : Math.min(pageSize, items.size() - offset);

    List<T> result = new ArrayList<>(limit);
    for (int i = 0; i < limit; i++) {
        T item = items.get(offset + i);
        result.add(item);
    }

    return result;
}



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