Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

2.7 KB
Raw Blame
package opensuite.ui;

import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.text.Collator;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * The sorter every sortable table uses. Swing's own compares a column as text
 * unless the model declares it a number column, so a column of counts sorted
 * 1, 10, 11, 2. This one compares numbers as numbers wherever it meets them:
 * a column that declares a type keeps that type's order, a column given its
 * own comparator keeps that, and any other is ordered by {@link #NATURAL}.
 */
public final class NumberSorter<M extends TableModel> extends TableRowSorter<M> {

    private static final Pattern NUMBER = Pattern.compile("-?\\d+(\\.\\d+)?");
    private static final Collator TEXT = Collator.getInstance();

    /** A blank first, then numbers in number order, then text as text. A number written as text counts as a number. */
    public static final Comparator<Object> NATURAL = (a, b) -> {
        Double x = number(a), y = number(b);
        boolean ba = blank(a), bb = blank(b);
        if (ba || bb) return ba == bb ? 0 : ba ? -1 : 1;
        if (x != null && y != null) return Double.compare(x, y);
        if (x != null || y != null) return x != null ? -1 : 1;
        return TEXT.compare(String.valueOf(a), String.valueOf(b));
    };

    private static boolean blank(Object o) { return o == null || (o instanceof String s && s.isBlank()); }

    private static Double number(Object o) {
        if (o instanceof Number n) return n.doubleValue();
        if (o instanceof String s) {
            String t = s.strip();
            if (t.length() <= 18 && NUMBER.matcher(t).matches()) return Double.valueOf(t);
        }
        return null;
    }

    private final Set<Integer> given = new HashSet<>();

    public NumberSorter(M model) { super(model); }

    @Override public void setComparator(int column, Comparator<?> comparator) {
        if (comparator == null) given.remove(column); else given.add(column);
        super.setComparator(column, comparator);
    }

    /** Whether the column is left to this sorter: no comparator of its own and no declared type but text. */
    private boolean natural(int column) {
        if (given != null && given.contains(column)) return false;
        Class<?> type = getModel().getColumnClass(column);
        return type == Object.class || type == String.class;
    }

    @Override public Comparator<?> getComparator(int column) {
        return natural(column) ? NATURAL : super.getComparator(column);
    }

    @Override protected boolean useToString(int column) {
        return !natural(column) && super.useToString(column);
    }
}