com.kopson.cite.smartlogmodel.SmartLogComparator.java Source code

Java tutorial

Introduction

Here is the source code for com.kopson.cite.smartlogmodel.SmartLogComparator.java

Source

/*******************************************************************************
 * Copyright (c) 2012 Piotr Kopka
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.kopson.cite.com/legal/epl-v10.html
 *
 * Contributors:
 *     Piotr Kopka
 *******************************************************************************/

package com.kopson.cite.smartlogmodel;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;

/**
 * Smart Log Comparator.
 * 
 * @author kopson
 *
 */
public class SmartLogComparator extends ViewerComparator {

    /**
     * Property index.
     */
    private int propertyIndex;

    /**
     * Sort order
     */
    private static final int DESCENDING = 1;

    /**
     * Direction
     */
    private int direction = DESCENDING;

    /**
     * The constructor.
     */
    public SmartLogComparator() {
        this.propertyIndex = 0;
        direction = DESCENDING;
    }

    /**
     * Get sort direction.
     * 
     * @return direction.
     */
    public int getDirection() {
        return direction == DESCENDING ? SWT.DOWN : SWT.UP;
    }

    /**
     * Set sort direction for column.
     * 
     * @param column.
     */
    public void setColumn(int column) {
        if (column == this.propertyIndex) {
            // Same column as last sort: toggle the direction
            direction = 1 - direction;
        } else {
            // New column: do an ascending sort
            this.propertyIndex = column;
            direction = DESCENDING;
        }
    }

    @Override
    public int compare(Viewer viewer, Object e1, Object e2) {

        SmartLogEntry p1 = (SmartLogEntry) e1;
        SmartLogEntry p2 = (SmartLogEntry) e2;

        int rc = 0;
        switch (propertyIndex) {
        case 0:
            rc = p1.getId() - p2.getId();
            break;
        case 1:
            rc = p1.getType().compareTo(p2.getType());
            break;
        case 2:
            rc = p1.getTag().compareTo(p2.getTag());
            break;
        case 3:
            rc = p1.getObject().compareTo(p2.getObject());
            break;
        default:
            rc = 0;
        }
        // If descending order, flip the direction
        if (direction == DESCENDING) {
            rc = -rc;
        }
        return rc;
    }

}