001/* 002 * Copyright 2006-2007 the original author or authors. 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 * https://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.springframework.batch.support; 017 018import java.io.IOException; 019import java.util.Comparator; 020 021import org.springframework.core.io.Resource; 022import org.springframework.util.Assert; 023 024/** 025 * Comparator to sort resources by the file last modified time. 026 * 027 * @author Dave Syer 028 * 029 */ 030public class LastModifiedResourceComparator implements Comparator<Resource> { 031 032 /** 033 * Compare the two resources by last modified time, so that a sorted list of 034 * resources will have oldest first. 035 * 036 * @throws IllegalArgumentException if one of the resources doesn't exist or 037 * its last modified date cannot be determined 038 * 039 * @see Comparator#compare(Object, Object) 040 */ 041 @Override 042 public int compare(Resource r1, Resource r2) { 043 Assert.isTrue(r1.exists(), "Resource does not exist: " + r1); 044 Assert.isTrue(r2.exists(), "Resource does not exist: " + r2); 045 try { 046 long diff = r1.getFile().lastModified() - r2.getFile().lastModified(); 047 return diff > 0 ? 1 : diff < 0 ? -1 : 0; 048 } 049 catch (IOException e) { 050 throw new IllegalArgumentException("Resource modification times cannot be determined (unexpected).", e); 051 } 052 } 053 054}