1 /*
2 * Copyright 2006-2007 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.springframework.batch.support;
17
18 import java.io.IOException;
19 import java.util.Comparator;
20
21 import org.springframework.core.io.Resource;
22 import org.springframework.util.Assert;
23
24 /**
25 * Comparator to sort resources by the file last modified time.
26 *
27 * @author Dave Syer
28 *
29 */
30 public class LastModifiedResourceComparator implements Comparator<Resource> {
31
32 /**
33 * Compare the two resources by last modified time, so that a sorted list of
34 * resources will have oldest first.
35 *
36 * @throws IllegalArgumentException if one of the resources doesn't exist or
37 * its last modified date cannot be determined
38 *
39 * @see Comparator#compare(Object, Object)
40 */
41 @Override
42 public int compare(Resource r1, Resource r2) {
43 Assert.isTrue(r1.exists(), "Resource does not exist: " + r1);
44 Assert.isTrue(r2.exists(), "Resource does not exist: " + r2);
45 try {
46 long diff = r1.getFile().lastModified() - r2.getFile().lastModified();
47 return diff > 0 ? 1 : diff < 0 ? -1 : 0;
48 }
49 catch (IOException e) {
50 throw new IllegalArgumentException("Resource modification times cannot be determined (unexpected).", e);
51 }
52 }
53
54 }