View Javadoc
1   /*
2    * Copyright (C) 2018, Konrad Windszus <konrad_w@gmx.de> 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  package org.eclipse.jgit.internal.transport.http;
11  
12  import java.nio.file.Path;
13  
14  import org.eclipse.jgit.transport.HttpConfig;
15  import org.eclipse.jgit.util.LRUMap;
16  
17  /**
18   * A cache of all known cookie files ({@link NetscapeCookieFile}). May contain
19   * at most {@code n} entries, where the least-recently used one is evicted as
20   * soon as more entries are added. The maximum number of entries (={@code n})
21   * can be set via the git config key {@code http.cookieFileCacheLimit}. By
22   * default it is set to 10.
23   * <p>
24   * The cache is global, i.e. it is shared among all consumers within the same
25   * Java process.
26   *
27   * @see NetscapeCookieFile
28   *
29   */
30  public class NetscapeCookieFileCache {
31  
32  	private final LRUMap<Path, NetscapeCookieFile> cookieFileMap;
33  
34  	private static NetscapeCookieFileCache instance;
35  
36  	private NetscapeCookieFileCache(HttpConfig config) {
37  		cookieFileMap = new LRUMap<>(config.getCookieFileCacheLimit(),
38  				config.getCookieFileCacheLimit());
39  	}
40  
41  	/**
42  	 * @param config
43  	 *            the config which defines the limit for this cache
44  	 * @return the singleton instance of the cookie file cache. If the cache has
45  	 *         already been created the given config is ignored (even if it
46  	 *         differs from the config, with which the cache has originally been
47  	 *         created)
48  	 */
49  	public static NetscapeCookieFileCache getInstance(HttpConfig config) {
50  		if (instance == null) {
51  			return new NetscapeCookieFileCache(config);
52  		}
53  		return instance;
54  	}
55  
56  	/**
57  	 * @param path
58  	 *            the path of the cookie file to retrieve
59  	 * @return the cache entry belonging to the requested file
60  	 */
61  	public NetscapeCookieFile getEntry(Path path) {
62  		if (!cookieFileMap.containsKey(path)) {
63  			synchronized (NetscapeCookieFileCache.class) {
64  				if (!cookieFileMap.containsKey(path)) {
65  					cookieFileMap.put(path, new NetscapeCookieFile(path));
66  				}
67  			}
68  		}
69  		return cookieFileMap.get(path);
70  	}
71  
72  }