com.microsoft.azure.keyvault.extensions.CachingKeyResolver Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of azure-keyvault-extensions Show documentation
Show all versions of azure-keyvault-extensions Show documentation
This package contains Microsoft Azure Key Vault SDK Extensions.
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.keyvault.extensions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.microsoft.azure.keyvault.KeyIdentifier;
import com.microsoft.azure.keyvault.core.IKey;
import com.microsoft.azure.keyvault.core.IKeyResolver;
/**
* The key resolver that caches the key after resolving to {@link IKey}.
*/
public class CachingKeyResolver implements IKeyResolver {
private final IKeyResolver keyResolver;
private final LoadingCache> cache;
/**
* Constructor.
* @param capacity the cache size
* @param keyResolver the key resolver
*/
public CachingKeyResolver(int capacity, final IKeyResolver keyResolver) {
this.keyResolver = keyResolver;
cache = CacheBuilder.newBuilder().maximumSize(capacity)
.build(new CacheLoader>() {
@Override
public ListenableFuture load(String kid) {
return keyResolver.resolveKeyAsync(kid);
}
});
}
@Override
public ListenableFuture resolveKeyAsync(String kid) {
KeyIdentifier keyIdentifier = new KeyIdentifier(kid);
if (keyIdentifier.version() == null) {
final ListenableFuture key = keyResolver.resolveKeyAsync(kid);
key.addListener(new Runnable() {
@Override
public void run() {
try {
cache.put(key.get().getKid(), key);
} catch (Exception e) {
// Key caching will occur on first read
}
}
},
MoreExecutors.directExecutor()
);
return key;
} else {
return cache.getUnchecked(kid);
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy