NetscapeCookieFileCache.java

  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. import java.nio.file.Path;

  12. import org.eclipse.jgit.transport.HttpConfig;
  13. import org.eclipse.jgit.util.LRUMap;

  14. /**
  15.  * A cache of all known cookie files ({@link NetscapeCookieFile}). May contain
  16.  * at most {@code n} entries, where the least-recently used one is evicted as
  17.  * soon as more entries are added. The maximum number of entries (={@code n})
  18.  * can be set via the git config key {@code http.cookieFileCacheLimit}. By
  19.  * default it is set to 10.
  20.  * <p>
  21.  * The cache is global, i.e. it is shared among all consumers within the same
  22.  * Java process.
  23.  *
  24.  * @see NetscapeCookieFile
  25.  *
  26.  */
  27. public class NetscapeCookieFileCache {

  28.     private final LRUMap<Path, NetscapeCookieFile> cookieFileMap;

  29.     private static NetscapeCookieFileCache instance;

  30.     private NetscapeCookieFileCache(HttpConfig config) {
  31.         cookieFileMap = new LRUMap<>(config.getCookieFileCacheLimit(),
  32.                 config.getCookieFileCacheLimit());
  33.     }

  34.     /**
  35.      * @param config
  36.      *            the config which defines the limit for this cache
  37.      * @return the singleton instance of the cookie file cache. If the cache has
  38.      *         already been created the given config is ignored (even if it
  39.      *         differs from the config, with which the cache has originally been
  40.      *         created)
  41.      */
  42.     public static NetscapeCookieFileCache getInstance(HttpConfig config) {
  43.         if (instance == null) {
  44.             return new NetscapeCookieFileCache(config);
  45.         }
  46.         return instance;
  47.     }

  48.     /**
  49.      * @param path
  50.      *            the path of the cookie file to retrieve
  51.      * @return the cache entry belonging to the requested file
  52.      */
  53.     public NetscapeCookieFile getEntry(Path path) {
  54.         if (!cookieFileMap.containsKey(path)) {
  55.             synchronized (NetscapeCookieFileCache.class) {
  56.                 if (!cookieFileMap.containsKey(path)) {
  57.                     cookieFileMap.put(path, new NetscapeCookieFile(path));
  58.                 }
  59.             }
  60.         }
  61.         return cookieFileMap.get(path);
  62.     }

  63. }