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

Scaling Policies

This post is part of a bigger topic Autoscaling Publishers in AWS . In a previous post we talked about the Auto Scaling Groups , but we didn't go into details on the Scaling Policies. This is the purpose of this blog post. As defined earlier, the Scaling Policies define the rules according to which the group size is increased or decreased. These rules are based on instance metrics (e.g. CPU), CloudWatch custom metrics, or even CloudWatch alarms and their states and values. We defined a Scaling Policy with Steps, called 'increase_group_size', which is triggered first by the CloudWatch Alarm 'Publish_Alarm' defined earlier. Also depending on the size of the monitored CloudWatch custom metric 'Waiting for Publish', the Scaling Policy with Steps can add a difference number of instances to the group. The scaling policy sets the number of instances in group to 1 if there are between 1000 and 2000 items Waiting for Publish in the queue. It also sets the

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

Toolkit - Dynamic Content Queries

This post if part of a series about the  File System Toolkit  - a custom content delivery API for SDL Tridion. This post presents the Dynamic Content Query capability. The requirements for the Toolkit API are that it should be able to provide CustomMeta queries, pagination, and sorting -- all on the file system, without the use third party tools (database, search engines, indexers, etc). Therefore I had to implement a simple database engine and indexer -- which is described in more detail in post Writing My Own Database Engine . The querying logic does not make use of cache. This means the query logic is executed every time. When models are requested, the models are however retrieved using the ModelFactory and those are cached. Query Class This is the main class for dynamic content queries. It is the entry point into the execution logic of a query. The class takes as parameter a Criterion (presented below) which triggers the execution of query in all sub-criteria of a Criterio