JGitKeyCache.java

  1. /*
  2.  * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch> 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.transport.sshd;

  11. import java.nio.file.Path;
  12. import java.security.KeyPair;
  13. import java.security.PrivateKey;
  14. import java.util.Map;
  15. import java.util.concurrent.ConcurrentHashMap;
  16. import java.util.concurrent.atomic.AtomicReference;
  17. import java.util.function.Function;

  18. import javax.security.auth.DestroyFailedException;

  19. /**
  20.  * A simple {@link KeyCache}. JGit uses one such cache in its
  21.  * {@link SshdSessionFactory} to avoid loading keys multiple times.
  22.  *
  23.  * @since 5.2
  24.  */
  25. public class JGitKeyCache implements KeyCache {

  26.     private AtomicReference<Map<Path, KeyPair>> cache = new AtomicReference<>(
  27.             new ConcurrentHashMap<>());

  28.     @Override
  29.     public KeyPair get(Path path,
  30.             Function<? super Path, ? extends KeyPair> loader) {
  31.         return cache.get().computeIfAbsent(path, loader);
  32.     }

  33.     @Override
  34.     public void close() {
  35.         Map<Path, KeyPair> map = cache.getAndSet(null);
  36.         if (map == null) {
  37.             return;
  38.         }
  39.         for (KeyPair k : map.values()) {
  40.             PrivateKey p = k.getPrivate();
  41.             try {
  42.                 p.destroy();
  43.             } catch (DestroyFailedException e) {
  44.                 // Ignore here. We did our best.
  45.             }
  46.         }
  47.         map.clear();
  48.     }
  49. }