2
* Licensed to the Apache Software Foundation (ASF) under one or more
3
* contributor license agreements. See the NOTICE file distributed with
4
* this work for additional information regarding copyright ownership.
5
* The ASF licenses this file to You under the Apache License, Version 2.0
6
* (the "License"); you may not use this file except in compliance with
7
* the License. You may obtain a copy of the License at
9
* http://www.apache.org/licenses/LICENSE-2.0
11
* Unless required by applicable law or agreed to in writing, software
12
* distributed under the License is distributed on an "AS IS" BASIS,
13
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
* See the License for the specific language governing permissions and
15
* limitations under the License.
18
package org.apache.solr.util;
21
import java.io.FileInputStream;
22
import java.io.FileNotFoundException;
23
import java.io.FilenameFilter;
24
import java.io.InputStream;
25
import java.util.ArrayList;
26
import java.util.Arrays;
27
import java.util.Collection;
28
import java.util.HashSet;
29
import java.util.List;
37
public class VersionedFile
39
/* Open the latest version of a file... fileName if that exists, or
40
* the last fileName.* after being sorted lexicographically.
41
* Older versions of the file are deleted (and queued for deletion if
44
public static InputStream getLatestFile(String dirName, String fileName) throws FileNotFoundException
46
Collection<File> oldFiles=null;
47
final String prefix = fileName+'.';
48
File f = new File(dirName, fileName);
49
InputStream is = null;
51
// there can be a race between checking for a file and opening it...
52
// the user may have just put a new version in and deleted an old version.
53
// try multiple times in a row.
54
for (int retry=0; retry<10 && is==null; retry++) {
57
File dir = new File(dirName);
58
String[] names = dir.list(new FilenameFilter() {
59
public boolean accept(File dir, String name) {
60
return name.startsWith(prefix);
64
f = new File(dir, names[names.length-1]);
65
oldFiles = new ArrayList<File>();
66
for (int i=0; i<names.length-1; i++) {
67
oldFiles.add(new File(dir, names[i]));
71
is = new FileInputStream(f);
72
} catch (Exception e) {
73
// swallow exception for now
77
// allow exception to be thrown from the final try.
79
is = new FileInputStream(f);
82
// delete old files only after we have successfuly opened the newest
83
if (oldFiles != null) {
90
private static final Set<File> deleteList = new HashSet<File>();
91
private static synchronized void delete(Collection<File> files) {
92
synchronized (deleteList) {
93
deleteList.addAll(files);
94
List<File> deleted = new ArrayList<File>();
95
for (File df : deleteList) {
98
// deleteList.remove(df);
100
} catch (SecurityException e) {
106
deleteList.removeAll(deleted);