001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.   
018 */
019package org.apache.wiki.pages;
020
021import org.apache.log4j.Logger;
022import org.apache.wiki.api.core.Page;
023
024import java.io.Serializable;
025import java.util.Comparator;
026import java.util.Date;
027
028/**
029 *  Compares the lastModified date of its arguments.  Both o1 and o2 MUST be WikiPage objects, or else you will receive a ClassCastException.
030 *  <p>
031 *  If the lastModified date is the same, then the next key is the page name. If the page name is also equal, then returns 0 for equality.
032 */
033public class PageTimeComparator implements Comparator< Page >, Serializable {
034    
035    private static final long serialVersionUID = 0L;
036    private static final Logger log = Logger.getLogger( PageTimeComparator.class );
037
038    /**
039     *  {@inheritDoc}
040     */
041    public int compare( final Page p1, final Page p2 ) {
042        if( p1 == null || p2 == null ) {
043            log.error( "W1 or W2 is NULL in PageTimeComparator!");
044            return 0; // FIXME: Is this correct?
045        }
046
047        final Date w1LastMod = p1.getLastModified();
048        final Date w2LastMod = p2.getLastModified();
049
050        if( w1LastMod == null ) {
051            log.error( "NULL MODIFY DATE WITH " + p1.getName() );
052            return 0;
053        } else if( w2LastMod == null ) {
054            log.error( "NULL MODIFY DATE WITH " + p2.getName() );
055            return 0;
056        }
057
058        // This gets most recent on top
059        final int timecomparison = w2LastMod.compareTo( w1LastMod );
060        if( timecomparison == 0 ) {
061            return p1.compareTo( p2 );
062        }
063
064        return timecomparison;
065    }
066
067}