/* * [SortBooks.java] * * Summary: Sort publish dates in descending order in embedded Insert macros. * * Copyright: (c) 2016-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: * 1.0 2016-06-26 initial version */ package com.mindprod.sortcode; import java.util.Comparator; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Sort publish dates in descending order in embedded Insert macros. * * @author Roedy Green, Canadian Mind Products * @version 1.0 2016-06-26 initial version * @since 2016-06-26 */ public class SortBooks implements Comparator { // TidyBookMacros: reflow Book macros. Update BookHead with recent title and published. Add missing published to BookHead. // RefreshInserts: refresh data on Insert macros from book page. Add missing published to book Insert. // InsertBookMarkers: put between books to make it easier to sort. One shot. // SortBooks: sort book Inserts on page so most recently published are first. // ProofreadInserts: check that sort worked. /** * will find publish date on Insert macro published=yyyy-mm-dd */ private static final Pattern PUBLISHED_GRABBER = Pattern.compile( "published=(\\d{4})(-\\d{2})?(-\\d{2})?" ); /** * @param s the entire block of text, somewhere containing published=yyyy-mm-dd * * @return yyyy-mm-dd */ private static String computeKey( String s ) { final Matcher m = PUBLISHED_GRABBER.matcher( s ); if ( m.find() ) { // found final String year = m.group( 1 ); if ( m.groupCount() >= 2 ) { final String month = m.group( 2 ); if ( m.groupCount() >= 3 ) { final String day = m.group( 3 ); return year + month + day; // including dashes. } else { return year + month; // including dash } } else { return year; } } else { return "0001-01-01"; } } // /method /** * Compare two String Objects each containing publish dates * * @param a first String to compare * @param b second String to compare * * @return +ve if a>b, 0 if a==b, -ve if a<b */ public final int compare( String a, String b ) { // reverse order to get descending sort return computeKey( b ).compareTo( computeKey( a ) ); } // /methods } // end class