protected LdapContext createLdapContext() throws KerberosOperationException {
    PrincipalKeyCredential administratorCredential = getAdministratorCredential();

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CONTEXT_FACTORY_CLASS);
    properties.put(Context.PROVIDER_URL, ldapUrl);
    properties.put(Context.SECURITY_PRINCIPAL, administratorCredential.getPrincipal());
    properties.put(Context.SECURITY_CREDENTIALS, String.valueOf(administratorCredential.getKey()));
    properties.put(Context.SECURITY_AUTHENTICATION, "simple");
    properties.put(Context.REFERRAL, "follow");

    if (ldapUrl.startsWith("ldaps")) {
      if (configuration.validateKerberosOperationSSLCertTrust()) {
        properties.put("java.naming.ldap.factory.socket", InternalSSLSocketFactoryNonTrusting.class.getName());
      } else {
        properties.put("java.naming.ldap.factory.socket", InternalSSLSocketFactoryTrusting.class.getName());
      }
    }

    try {
      return createInitialLdapContext(properties, null);
    } catch (CommunicationException e) {
      Throwable rootCause = e.getRootCause();

      String message = String.format("Failed to communicate with the Active Directory at %s: %s", ldapUrl, e.getMessage());
      LOG.warn(message, e);

      if (rootCause instanceof SSLHandshakeException) {
        throw new KerberosKDCSSLConnectionException(message, e);
      } else {
        throw new KerberosKDCConnectionException(message, e);
      }
    } catch (AuthenticationException e) {
      String message = String.format("Failed to authenticate with the Active Directory at %s: %s", ldapUrl, e.getMessage());
      LOG.warn(message, e);
      throw new KerberosAdminAuthenticationException(message, e);
    } catch (NamingException e) {
      String error = e.getMessage();

      if (StringUtils.isEmpty(error)) {
        String message = String.format("Failed to communicate with the Active Directory at %s: %s", ldapUrl, e.getMessage());
        LOG.warn(message, e);

        if (error.startsWith("Cannot parse url:")) {
          throw new KerberosKDCConnectionException(message, e);
        } else {
          throw new KerberosOperationException(message, e);
        }
      } else {
        throw new KerberosOperationException("Unexpected error condition", e);
      }
    }
  }
Helper method to create the LDAP context needed to interact with the Active Directory.

@return the relevant LdapContext
@throws KerberosKDCConnectionException       if a connection to the KDC cannot be made
@throws KerberosAdminAuthenticationException if the administrator credentials fail to authenticate
@throws KerberosRealmException               if the realm does not map to a KDC
@throws KerberosOperationException           if an unexpected error occurred
ambari-server/src/main/java/org/apache/ambari/server/serveraction/kerberos/ADKerberosOperationHandler.java