package ru.yandex.qe.http.certificates;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.annotation.Nonnull;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang3.ArrayUtils;

/**
 * Merges two trust managers into one.
 * <p/>
 * {@literal http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/SSLContext.html#init(javax.net.ssl.KeyManager[],
 * javax.net.ssl.TrustManager[], java.security.SecureRandom)}
 *
 * @author nkey
 * @since 17.03.14
 */
public class CompositeX509TrustManager implements X509TrustManager {
    @Nonnull
    private final X509TrustManager first;
    @Nonnull
    private final X509TrustManager second;

    public CompositeX509TrustManager(@Nonnull X509TrustManager first, @Nonnull X509TrustManager second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        try {
            first.checkClientTrusted(x509Certificates, s);
        } catch (CertificateException e) {
            second.checkClientTrusted(x509Certificates, s);
        }
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        try {
            first.checkServerTrusted(x509Certificates, s);
        } catch (CertificateException e) {
            second.checkServerTrusted(x509Certificates, s);
        }
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return ArrayUtils.addAll(first.getAcceptedIssuers(), second.getAcceptedIssuers());
    }
}
