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...

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...