private X509Certificate[] generateKeyChainIncludingCA(boolean expired, boolean multipleEndCert, boolean endCert0Valid, boolean endCert1Valid)
            throws CertificateException, NoSuchAlgorithmException {
        // For testing, we might create another end certificate
        int nrOfCerts = multipleEndCert ? 4 : 3;
        KeyPair[] keyPairs = new KeyPair[nrOfCerts];
        for (int i = 0; i < nrOfCerts; i++) {
            keyPairs[i] = TestSslUtils.generateKeyPair("RSA");
        }
        X509Certificate[] certs = new X509Certificate[nrOfCerts];
        int endCertDaysValidBeforeNow = 1;
        // If using 0 or a negative value, the generated certificate will be expired
        int endCertDaysValidAfterNow = expired ? 0 : 1;
        // Generate root CA
        int caIndex = nrOfCerts - 1;
        certs[caIndex] = TestSslUtils.generateSignedCertificate("CN=CA", keyPairs[caIndex], 365,
                365, null, null, "SHA512withRSA", true, false, false);
        int intermediateCertIndex = caIndex - 1;
        certs[intermediateCertIndex] = TestSslUtils.generateSignedCertificate("CN=Intermediate CA",
                keyPairs[intermediateCertIndex], 365, 365, certs[caIndex].getSubjectX500Principal().getName(), keyPairs[caIndex],
                "SHA512withRSA", true, false, false);
        for (int currIndex = intermediateCertIndex - 1; currIndex >= 0; currIndex--) {
            // When generating multiple end certificates, 
            boolean endCertValid = (currIndex == 0) ? endCert0Valid : endCert1Valid;
            if (endCertValid) {
                // Generate a valid end certificate, i.e. one that is signed by our intermediate
                // CA
                certs[currIndex] = TestSslUtils.generateSignedCertificate("CN=kafka", keyPairs[currIndex],
                        endCertDaysValidBeforeNow, endCertDaysValidAfterNow,
                        certs[intermediateCertIndex].getSubjectX500Principal().getName(), keyPairs[intermediateCertIndex], "SHA512withRSA", false, true, true);
            } else {
                // Generate an invalid end certificate, by creating a self-signed one.
                certs[currIndex] = TestSslUtils.generateSignedCertificate("C=GB, L=London, CN=kafka", keyPairs[currIndex],
                        endCertDaysValidBeforeNow, endCertDaysValidAfterNow,
                        null, null, "SHA512withRSA", false, true, true);
            }
        }
        return certs;
    }
This helper method generates a valid key chain with one end entity
(client/server cert), one intermediate certificate authority and one 
root certificate authority (self-signed)

@return
@throws CertificateException
@throws NoSuchAlgorithmException
clients/src/test/java/org/apache/kafka/common/security/ssl/CommonNameLoggingTrustManagerFactoryWrapperTest.java