View Javadoc
1   /*
2    * Copyright (C) 2015, Google Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.internal.storage.file;
12  
13  import static java.nio.charset.StandardCharsets.UTF_8;
14  
15  import java.io.BufferedReader;
16  import java.io.File;
17  import java.io.FileInputStream;
18  import java.io.IOException;
19  import java.io.InputStreamReader;
20  import java.io.Reader;
21  
22  import org.eclipse.jgit.lib.AnyObjectId;
23  import org.eclipse.jgit.lib.MutableObjectId;
24  import org.eclipse.jgit.lib.ObjectIdOwnerMap;
25  import org.eclipse.jgit.lib.ObjectIdSet;
26  
27  /**
28   * Lazily loads a set of ObjectIds, one per line.
29   */
30  public class LazyObjectIdSetFile implements ObjectIdSet {
31  	private final File src;
32  	private ObjectIdOwnerMap<Entry> set;
33  
34  	/**
35  	 * Create a new lazy set from a file.
36  	 *
37  	 * @param src
38  	 *            the source file.
39  	 */
40  	public LazyObjectIdSetFile(File src) {
41  		this.src = src;
42  	}
43  
44  	/** {@inheritDoc} */
45  	@Override
46  	public boolean contains(AnyObjectId objectId) {
47  		if (set == null) {
48  			set = load();
49  		}
50  		return set.contains(objectId);
51  	}
52  
53  	private ObjectIdOwnerMap<Entry> load() {
54  		ObjectIdOwnerMap<Entry> r = new ObjectIdOwnerMap<>();
55  		try (FileInputStream fin = new FileInputStream(src);
56  				Reader rin = new InputStreamReader(fin, UTF_8);
57  				BufferedReader br = new BufferedReader(rin)) {
58  			MutableObjectId id = new MutableObjectId();
59  			for (String line; (line = br.readLine()) != null;) {
60  				id.fromString(line);
61  				if (!r.contains(id)) {
62  					r.add(new Entry(id));
63  				}
64  			}
65  		} catch (IOException e) {
66  			// Ignore IO errors accessing the lazy set.
67  		}
68  		return r;
69  	}
70  
71  	static class Entry extends ObjectIdOwnerMap.Entry {
72  		Entry(AnyObjectId id) {
73  			super(id);
74  		}
75  	}
76  }