/* * [ByAuthor.java] * * Summary: Comparator to sort HTML menu items by author then title. * * Copyright: (c) 2002-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 2.0 2007-04-12 merge versions from Acer and Steve. */ package com.mindprod.stores; import java.util.Comparator; /** * Comparator to sort HTML menu items by author then title. * * @author Roedy Green, Canadian Mind Products * @version 2.0 2007-04-12 merge versions from Acer and Steve. * @since 2002 */ class ByAuthor implements Comparator { public int compare( String o1, String o2 ) { // line looks like // {Hegemony Or Survival by Noam Chomsky} // or {Mission Accomplished by Christopher Cerf and Victor S. Navasky} final int b1 = o1.indexOf( " by " ); final int b2 = o2.indexOf( " by " ); if ( b1 < 0 ) { throw new IllegalArgumentException( "missing by " + o1 ); } if ( b2 < 0 ) { throw new IllegalArgumentException( "missing by " + o2 ); } final int t1 = o1.indexOf( " and ", b1 + 4 ); final int t2 = o2.indexOf( " and ", b2 + 4 ); final String tail1; final String tail2; if ( t1 < 0 ) { tail1 = o1.substring( b1 + 4 ); } else { tail1 = o1.substring( 0, t1 ); } if ( t2 < 0 ) { tail2 = o2.substring( b2 + 4 ); } else { tail2 = o2.substring( 0, t2 ); } final String surname1 = tail1.substring( tail1.lastIndexOf( ' ' ) + 1 ); final String surname2 = tail2.substring( tail2.lastIndexOf( ' ' ) + 1 ); int diff = surname1.compareToIgnoreCase( surname2 ); if ( diff != 0 ) { return diff; } // break tie by examining title. final int g1 = o1.indexOf( '>' ); final int g2 = o2.indexOf( '>' ); if ( g1 < 0 ) { throw new IllegalArgumentException( "missing > " + o1 ); } if ( g2 < 0 ) { throw new IllegalArgumentException( "missing > " + o2 ); } String title1 = o1.substring( g1 + 1 ); String title2 = o2.substring( g2 + 1 ); if ( title1.startsWith( "The " ) ) { title1 = title1.substring( 4 ); } if ( title2.startsWith( "The " ) ) { title2 = title2.substring( 4 ); } if ( title1.startsWith( "A " ) ) { title1 = title1.substring( 2 ); } if ( title2.startsWith( "A " ) ) { title2 = title2.substring( 2 ); } return title1.compareToIgnoreCase( title2 ); } }