// 
// Decompiled by Procyon v0.6.0
// 

package com.nimbusds.jose.jwk.source;

import com.nimbusds.jose.util.IOUtils;
import com.nimbusds.jose.KeySourceException;
import com.nimbusds.jose.jwk.JWK;
import java.util.List;
import com.nimbusds.jose.jwk.JWKSelector;
import java.util.Objects;
import com.nimbusds.jose.shaded.jcip.ThreadSafe;
import java.io.Closeable;
import com.nimbusds.jose.proc.SecurityContext;

@ThreadSafe
public class JWKSourceWithFailover<C extends SecurityContext> implements JWKSource<C>, Closeable
{
    private final JWKSource<C> jwkSource;
    private final JWKSource<C> failoverJWKSource;
    
    public JWKSourceWithFailover(final JWKSource<C> jwkSource, final JWKSource<C> failoverJWKSource) {
        Objects.requireNonNull(jwkSource, "The primary JWK source must not be null");
        this.jwkSource = jwkSource;
        this.failoverJWKSource = failoverJWKSource;
    }
    
    private List<JWK> failover(final Exception exception, final JWKSelector jwkSelector, final C context) throws KeySourceException {
        try {
            return this.failoverJWKSource.get(jwkSelector, context);
        }
        catch (final KeySourceException kse) {
            throw new KeySourceException(exception.getMessage() + "; Failover JWK source retrieval failed with: " + kse.getMessage(), kse);
        }
    }
    
    @Override
    public List<JWK> get(final JWKSelector jwkSelector, final C context) throws KeySourceException {
        try {
            return this.jwkSource.get(jwkSelector, context);
        }
        catch (final Exception e) {
            return this.failover(e, jwkSelector, context);
        }
    }
    
    @Override
    public void close() {
        if (this.jwkSource instanceof Closeable) {
            IOUtils.closeSilently((Closeable)this.jwkSource);
        }
        if (this.failoverJWKSource instanceof Closeable) {
            IOUtils.closeSilently((Closeable)this.failoverJWKSource);
        }
    }
}
