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.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.api.core.Page;
024
025import java.io.Serializable;
026import java.util.Comparator;
027import java.util.Date;
028
029/**
030 *  Compares the lastModified date of its arguments.  Both o1 and o2 MUST be WikiPage objects, or else you will receive a ClassCastException.
031 *  <p>
032 *  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.
033 */
034public class PageTimeComparator implements Comparator< Page >, Serializable {
035    
036    private static final long serialVersionUID = 0L;
037    private static final Logger LOG = LogManager.getLogger( PageTimeComparator.class );
038
039    /**
040     *  {@inheritDoc}
041     */
042    @Override
043    public int compare(final Page p1, final Page p2 ) {
044        if( p1 == null || p2 == null ) {
045            LOG.error( "W1 or W2 is NULL in PageTimeComparator!");
046            return 0; // FIXME: Is this correct?
047        }
048
049        final Date w1LastMod = p1.getLastModified();
050        final Date w2LastMod = p2.getLastModified();
051
052        if( w1LastMod == null ) {
053            LOG.error( "NULL MODIFY DATE WITH " + p1.getName() );
054            return 0;
055        } else if( w2LastMod == null ) {
056            LOG.error( "NULL MODIFY DATE WITH " + p2.getName() );
057            return 0;
058        }
059
060        // This gets most recent on top
061        final int timecomparison = w2LastMod.compareTo( w1LastMod );
062        if( timecomparison == 0 ) {
063            return p1.compareTo( p2 );
064        }
065
066        return timecomparison;
067    }
068
069}