001/**
002 * Copyright 2015 DuraSpace, Inc.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.fcrepo.http.commons.api.rdf;
017
018import java.util.Comparator;
019
020import com.hp.hpl.jena.graph.Triple;
021import com.hp.hpl.jena.shared.PrefixMapping;
022
023/**
024 * Comparator to sort a list of Quads by subject, predicate, and object
025 * to ensure a consistent order for human-readable output
026 *
027 * @author awoods
028 */
029public class TripleOrdering implements Comparator<Triple> {
030
031    private final PrefixMapping prefixMapping;
032
033    /**
034     * When sorting predicates, take into account the given PrefixMapping
035     * @param prefixMapping the prefix mapping
036     */
037    public TripleOrdering(final PrefixMapping prefixMapping) {
038        super();
039
040        this.prefixMapping = prefixMapping;
041    }
042
043    @Override
044    public int compare(final Triple left, final Triple right) {
045
046        final int s =
047                left.getSubject().toString(prefixMapping, false).compareTo(
048                        right.getSubject().toString(prefixMapping, false));
049
050        if (s != 0) {
051            return s;
052        }
053
054        final int p =
055                left.getPredicate().toString(prefixMapping, false).compareTo(
056                        right.getPredicate().toString(prefixMapping, false));
057
058        if (p != 0) {
059            return p;
060        }
061
062        return left.getObject().toString(false).compareTo(
063                right.getObject().toString(false));
064
065    }
066
067}