View Javadoc
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  
12  import java.nio.file.Path;
13  import java.security.KeyPair;
14  import java.security.PrivateKey;
15  import java.util.Map;
16  import java.util.concurrent.ConcurrentHashMap;
17  import java.util.concurrent.atomic.AtomicReference;
18  import java.util.function.Function;
19  
20  import javax.security.auth.DestroyFailedException;
21  
22  /**
23   * A simple {@link KeyCache}. JGit uses one such cache in its
24   * {@link SshdSessionFactory} to avoid loading keys multiple times.
25   *
26   * @since 5.2
27   */
28  public class JGitKeyCache implements KeyCache {
29  
30  	private AtomicReference<Map<Path, KeyPair>> cache = new AtomicReference<>(
31  			new ConcurrentHashMap<>());
32  
33  	@Override
34  	public KeyPair get(Path path,
35  			Function<? super Path, ? extends KeyPair> loader) {
36  		return cache.get().computeIfAbsent(path, loader);
37  	}
38  
39  	@Override
40  	public void close() {
41  		Map<Path, KeyPair> map = cache.getAndSet(null);
42  		if (map == null) {
43  			return;
44  		}
45  		for (KeyPair k : map.values()) {
46  			PrivateKey p = k.getPrivate();
47  			try {
48  				p.destroy();
49  			} catch (DestroyFailedException e) {
50  				// Ignore here. We did our best.
51  			}
52  		}
53  		map.clear();
54  	}
55  }