View Javadoc
1   /*
2    * Copyright (C) 2017, 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.dfs;
12  
13  import java.io.IOException;
14  import java.util.ArrayList;
15  import java.util.Collections;
16  import java.util.List;
17  
18  import org.eclipse.jgit.internal.storage.reftable.ReftableReader;
19  
20  /**
21   * Tracks multiple open
22   * {@link org.eclipse.jgit.internal.storage.reftable.ReftableReader} instances.
23   */
24  public class DfsReftableStack implements AutoCloseable {
25  	/**
26  	 * Opens a stack of tables for reading.
27  	 *
28  	 * @param ctx
29  	 *            context to read the tables with. This {@code ctx} will be
30  	 *            retained by the stack and each of the table readers.
31  	 * @param files
32  	 *            the tables to open.
33  	 * @return stack reference to close the tables.
34  	 * @throws java.io.IOException
35  	 *             a table could not be opened
36  	 */
37  	public static DfsReftableStack open(DfsReader ctx, List<DfsReftable> files)
38  			throws IOException {
39  		DfsReftableStack stack = new DfsReftableStack(files.size());
40  		boolean close = true;
41  		try {
42  			for (DfsReftable t : files) {
43  				stack.files.add(t);
44  				stack.tables.add(t.open(ctx));
45  			}
46  			close = false;
47  			return stack;
48  		} finally {
49  			if (close) {
50  				stack.close();
51  			}
52  		}
53  	}
54  
55  	private final List<DfsReftable> files;
56  	private final List<ReftableReader> tables;
57  
58  	private DfsReftableStack(int tableCnt) {
59  		this.files = new ArrayList<>(tableCnt);
60  		this.tables = new ArrayList<>(tableCnt);
61  	}
62  
63  	/**
64  	 * Get unmodifiable list of DfsRefatble files
65  	 *
66  	 * @return unmodifiable list of DfsRefatble files, in the same order the
67  	 *         files were passed to {@link #open(DfsReader, List)}.
68  	 */
69  	public List<DfsReftable> files() {
70  		return Collections.unmodifiableList(files);
71  	}
72  
73  	/**
74  	 * Get unmodifiable list of tables
75  	 *
76  	 * @return unmodifiable list of tables, in the same order the files were
77  	 *         passed to {@link #open(DfsReader, List)}.
78  	 */
79  	public List<ReftableReader> readers() {
80  		return Collections.unmodifiableList(tables);
81  	}
82  
83  	/** {@inheritDoc} */
84  	@Override
85  	public void close() {
86  		for (ReftableReader t : tables) {
87  			try {
88  				t.close();
89  			} catch (IOException e) {
90  				// Ignore close failures.
91  			}
92  		}
93  	}
94  }