Prepare a new LDAP connection.

@param ldapURL the ldap uRL
@return connection factory
196363
protected ConnectionFactory prepareConnectionFactory(final String ldapURL) {
        val cc = ConnectionConfig.newConnectionConfig(this.connectionConfig);
        cc.setLdapUrl(ldapURL);
        return new DefaultConnectionFactory(cc);
    }
1006141
def initialize(self):
        

        try:
            conn = ldap.initialize('{0}://{1}:{2}'.format(
                current_app.config['LDAP_SCHEMA'],
                current_app.config['LDAP_HOST'],
                current_app.config['LDAP_PORT']))
            conn.set_option(ldap.OPT_NETWORK_TIMEOUT,
                            current_app.config['LDAP_TIMEOUT'])
            conn = self._set_custom_options(conn)
            conn.protocol_version = ldap.VERSION3
            if current_app.config['LDAP_USE_TLS']:
                conn.start_tls_s()
            return conn
        except ldap.LDAPError as e:
            raise LDAPException(self.error(e.args))
932077
protected URLConnection createURLConnection() throws Exception {
        URL url = getResourceURL();
        if (url == null) return null;
        URLConnection uc = url.openConnection();
        // encoding should be applied when connecting
        return uc;
    }
13180
public Object createConnectionFactory(
            final ConnectionManager connectionManager) {

        if (TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, "createConnectionFactory",
                    connectionManager);
        }

        final Object connectionFactory = new SibRaConnectionFactory(this,
                connectionManager);

        if (TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, "createConnectionFactory",
                    connectionFactory);
        }
        return connectionFactory;

    }
875738
public static LdapException create(LDAPException e) {
        return new LdapException(DefaultLdapResultCodeFactory.convertResultCode(e.getResultCode()),
                e.getDiagnosticMessage(), e);
    }
1309743
protected Connection createConnection() throws LdapException {
        LOGGER.debug("Establishing a connection...");
        val connection = this.connectionFactory.getConnection();
        connection.open();
        return connection;
    }
333309
protected SessionFactory createSessionFactory( ConnectionProvider connectionProvider, RetryLogic retryLogic,
            Config config )
    {
        return new SessionFactoryImpl( connectionProvider, retryLogic, config );
    }
785178
public static ConnectionConfig newLdaptiveConnectionConfig(final AbstractLdapProperties l) {
        if (StringUtils.isBlank(l.getLdapUrl())) {
            throw new IllegalArgumentException("LDAP url cannot be empty/blank");
        }

        LOGGER.debug("Creating LDAP connection configuration for [{}]", l.getLdapUrl());
        val cc = new ConnectionConfig();

        val urls = l.getLdapUrl().contains(" ")
            ? l.getLdapUrl()
            : String.join(" ", l.getLdapUrl().split(","));
        LOGGER.debug("Transformed LDAP urls from [{}] to [{}]", l.getLdapUrl(), urls);
        cc.setLdapUrl(urls);

        cc.setUseSSL(l.isUseSsl());
        cc.setUseStartTLS(l.isUseStartTls());
        cc.setConnectTimeout(Beans.newDuration(l.getConnectTimeout()));
        cc.setResponseTimeout(Beans.newDuration(l.getResponseTimeout()));

        if (StringUtils.isNotBlank(l.getConnectionStrategy())) {
            val strategy = AbstractLdapProperties.LdapConnectionStrategy.valueOf(l.getConnectionStrategy());
            switch (strategy) {
                case RANDOM:
                    cc.setConnectionStrategy(new RandomConnectionStrategy());
                    break;
                case DNS_SRV:
                    cc.setConnectionStrategy(new DnsSrvConnectionStrategy());
                    break;
                case ACTIVE_PASSIVE:
                    cc.setConnectionStrategy(new ActivePassiveConnectionStrategy());
                    break;
                case ROUND_ROBIN:
                    cc.setConnectionStrategy(new RoundRobinConnectionStrategy());
                    break;
                case DEFAULT:
                default:
                    cc.setConnectionStrategy(new DefaultConnectionStrategy());
                    break;
            }
        }

        if (l.getTrustCertificates() != null) {
            LOGGER.debug("Creating LDAP SSL configuration via trust certificates [{}]", l.getTrustCertificates());
            val cfg = new X509CredentialConfig();
            cfg.setTrustCertificates(l.getTrustCertificates());
            cc.setSslConfig(new SslConfig(cfg));
        } else if (l.getTrustStore() != null || l.getKeystore() != null) {
            val cfg = new KeyStoreCredentialConfig();
            if (l.getTrustStore() != null) {
                LOGGER.trace("Creating LDAP SSL configuration with truststore [{}]", l.getTrustStore());
                cfg.setTrustStore(l.getTrustStore());
                cfg.setTrustStoreType(l.getTrustStoreType());
                cfg.setTrustStorePassword(l.getTrustStorePassword());
            }
            if (l.getKeystore() != null) {
                LOGGER.trace("Creating LDAP SSL configuration via keystore [{}]", l.getKeystore());
                cfg.setKeyStore(l.getKeystore());
                cfg.setKeyStorePassword(l.getKeystorePassword());
                cfg.setKeyStoreType(l.getKeystoreType());
            }
            cc.setSslConfig(new SslConfig(cfg));
        } else {
            LOGGER.debug("Creating LDAP SSL configuration via the native JVM truststore");
            cc.setSslConfig(new SslConfig());
        }

        val sslConfig = cc.getSslConfig();
        if (sslConfig != null) {
            switch (l.getHostnameVerifier()) {
                case ANY:
                    sslConfig.setHostnameVerifier(new AllowAnyHostnameVerifier());
                    break;
                case DEFAULT:
                default:
                    sslConfig.setHostnameVerifier(new DefaultHostnameVerifier());
                    break;
            }
        }

        if (StringUtils.isNotBlank(l.getSaslMechanism())) {
            LOGGER.debug("Creating LDAP SASL mechanism via [{}]", l.getSaslMechanism());

            val bc = new BindConnectionInitializer();
            val sc = getSaslConfigFrom(l);

            if (StringUtils.isNotBlank(l.getSaslAuthorizationId())) {
                sc.setAuthorizationId(l.getSaslAuthorizationId());
            }
            sc.setMutualAuthentication(l.getSaslMutualAuth());
            if (StringUtils.isNotBlank(l.getSaslQualityOfProtection())) {
                sc.setQualityOfProtection(QualityOfProtection.valueOf(l.getSaslQualityOfProtection()));
            }
            if (StringUtils.isNotBlank(l.getSaslSecurityStrength())) {
                sc.setSecurityStrength(SecurityStrength.valueOf(l.getSaslSecurityStrength()));
            }
            bc.setBindSaslConfig(sc);
            cc.setConnectionInitializer(bc);
        } else if (StringUtils.equals(l.getBindCredential(), "*") && StringUtils.equals(l.getBindDn(), "*")) {
            LOGGER.debug("Creating LDAP fast-bind connection initializer");
            cc.setConnectionInitializer(new FastBindOperation.FastBindConnectionInitializer());
        } else if (StringUtils.isNotBlank(l.getBindDn()) && StringUtils.isNotBlank(l.getBindCredential())) {
            LOGGER.debug("Creating LDAP bind connection initializer via [{}]", l.getBindDn());
            cc.setConnectionInitializer(new BindConnectionInitializer(l.getBindDn(), new Credential(l.getBindCredential())));
        }
        return cc;
    }
703920
public ConnectionFactory<?> getConnectionFactory(String providerId) {
		ConnectionFactory<?> connectionFactory = connectionFactories.get(providerId);
		if (connectionFactory == null) {
			throw new IllegalArgumentException("No connection factory for service provider '" + providerId + "' is registered");
		}
		return connectionFactory;
	}
336497
public static LdapException create(ILdapResult result) {
        return new LdapException(result.getResultCode(), result.getMessage(), null);
    }
615270
public SmtpConnectionFactory build() {
    if (session == null) {
      session = Session.getInstance(new Properties());
    }

    TransportStrategy transportStrategy = protocol == null ? newSessiontStrategy() : newProtocolStrategy(protocol);

    ConnectionStrategy connectionStrategy;
    if (host == null && port == -1 && username == null && password == null) {
      connectionStrategy = newConnectionStrategy();
    } else {
      connectionStrategy = newConnectionStrategy(host, port, username, password);
    }

    return new SmtpConnectionFactory(session, transportStrategy, connectionStrategy, defaultTransportListeners);
  }
120640
public static URLConnection prepareForSSL( final URLConnection connection )
    {
        NullArgumentException.validateNotNull( connection, "url connection cannot be null" );
        URLConnection conn = connection;
        if( conn instanceof JarURLConnection )
        {
            try
            {
                conn = ( (JarURLConnection) connection ).getJarFileURL().openConnection();
                conn.connect();
            }
            catch( IOException e )
            {
                throw new RuntimeException( "Could not prepare connection for HTTPS.", e );
            }
        }
        if( conn instanceof HttpsURLConnection )
        {
            try
            {
                SSLContext ctx = SSLContext.getInstance( "SSLv3" );
                ctx.init( null, new TrustManager[]{ new AllCertificatesTrustManager() }, null );
                ( (HttpsURLConnection) conn ).setSSLSocketFactory( ctx.getSocketFactory() );
            }
            catch( KeyManagementException e )
            {
                throw new RuntimeException( "Could not prepare connection for HTTPS.", e );
            }
            catch( NoSuchAlgorithmException e )
            {
                throw new RuntimeException( "Could not prepare connection for HTTPS.", e );
            }

        }
        return connection;
    }
907034
protected function initiateLdapConnection($server = null)
    {
        list($ldapUrl, $server) = $this->getLdapUrl($server);

        $this->connection = @ldap_connect($ldapUrl);
        if (!$this->connection) {
            throw new LdapConnectionException(
                sprintf("Failed to initiate LDAP connection with URI: %s", $ldapUrl)
            );
        }

        foreach ($this->config->getLdapOptions() as $option => $value) {
            if (!ldap_set_option($this->connection, $option, $value)) {
                throw new LdapConnectionException("Failed to set LDAP connection option.");
            }
        }

        if ($this->config->getUseTls() && !@ldap_start_tls($this->connection)) {
            throw new LdapConnectionException(
                sprintf("Failed to start TLS: %s", $this->getLastError()),
                $this->getExtendedErrorNumber()
            );
        }

        $this->server = $server;
    }
1096043
protected URLConnection openConnection(URL url)
        throws IOException
    {
        URLConnection conn = url.openConnection();

        conn.setDoOutput(true);

        if (_basicAuth != null)
            conn.setRequestProperty("Authorization", _basicAuth);
        else if (_user != null && _password != null) {
            _basicAuth = "Basic " + base64(_user + ":" + _password);
            conn.setRequestProperty("Authorization", _basicAuth);
        }

        return conn;
    }
348078
protected HttpURLConnection openConnection(String url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS);
    connection.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setDoInput(true);
    return connection;
  }
401141
public function connect()
    {
        $this->connect = ldap_connect($this->hostname, $this->port);

        if (!$this->connect) {
            throw new ConnectionException($this);
        }

        // Set Ldap Version to 3
        ldap_set_option($this->connect, LDAP_OPT_PROTOCOL_VERSION, 3);

        if (!is_null($this->username) && !is_null($this->password)) {
            if (!@ldap_bind($this->connect, $this->username, $this->password)) {
                throw new BadIdentificationException($this);
            }
        }

        return new Client($this->connect);
    }
506587
public static EntryResolver newSearchEntryResolver(final LdapAuthenticationProperties l) {
        final PooledSearchEntryResolver entryResolver = new PooledSearchEntryResolver();
        entryResolver.setBaseDn(l.getBaseDn());
        entryResolver.setUserFilter(l.getUserFilter());
        entryResolver.setSubtreeSearch(l.isSubtreeSearch());
        entryResolver.setConnectionFactory(LdaptiveAuthenticatorBuilder.newPooledConnectionFactory(l));
        return entryResolver;
    }