/*
   * Returns the list of root certificates
   * The list of certificates we received is an array of certificates
   * we have to determine
   * 1) how many chain do we have (a chain stops when verifier of a cert is
   * not the signer of the next cert in the list
   * 2) build a cert with the leaf signer and the root verifier for each chain
   */
  public CertificatePair[] getRootCertificates() {
    if (rootCertificates == null) {
      rootCertificates = new CertificatePair[0];
      List rootCertificatesList = new ArrayList();
      if (certificates != null && certificates.size() > 0) {
        Iterator iter = certificates.iterator();
        while (iter.hasNext()) {

          Certificate[] certs = (Certificate[]) iter.next();
          if (certs != null && certs.length > 0) {

            CertificatePair pair = new CertificatePair();
            pair.setIssuer(certs[0]);

            for (int i = 0; i < certs.length - 1; i++) {
              X509Certificate x509certRoot = (X509Certificate) certs[i];
              X509Certificate x509certIssuer = (X509Certificate) certs[i + 1];
              if (!x509certRoot.getIssuerDN().equals(x509certIssuer.getSubjectDN())) {
                pair.setRoot(x509certRoot);
                if (!rootCertificatesList.contains(pair)) {
                  rootCertificatesList.add(pair);
                }
                pair = new CertificatePair();
                pair.setIssuer(x509certIssuer);
              }
            }

            // add the latest one
            if (pair != null) {
              pair.setRoot(certs[certs.length - 1]);
              if (!rootCertificatesList.contains(pair)) {
                rootCertificatesList.add(pair);
              }
            }
          }
        }
      }

      if (rootCertificatesList.size() > 0) {
        rootCertificates = new CertificatePair[rootCertificatesList.size()];
        rootCertificatesList.toArray(rootCertificates);
      }
    }
    return rootCertificates;
  }