New connection config connection config.

@param l the ldap properties
@return the connection config
6385
public static ConnectionConfig newConnectionConfig(final AbstractLdapProperties l) {
        final ConnectionConfig cc = new ConnectionConfig();
        final String urls = Arrays.stream(l.getLdapUrl().split(",")).collect(Collectors.joining(" "));
        LOGGER.debug("Transformed LDAP urls from [{}] to [{}]", l.getLdapUrl(), urls);
        cc.setLdapUrl(urls);
        cc.setUseSSL(l.isUseSsl());
        cc.setUseStartTLS(l.isUseStartTls());
        cc.setConnectTimeout(newDuration(l.getConnectTimeout()));

        if (l.getTrustCertificates() != null) {
            final X509CredentialConfig cfg = new X509CredentialConfig();
            cfg.setTrustCertificates(l.getTrustCertificates());
            cc.setSslConfig(new SslConfig(cfg));
        } else if (l.getKeystore() != null) {
            final KeyStoreCredentialConfig cfg = new KeyStoreCredentialConfig();
            cfg.setKeyStore(l.getKeystore());
            cfg.setKeyStorePassword(l.getKeystorePassword());
            cfg.setKeyStoreType(l.getKeystoreType());
            cc.setSslConfig(new SslConfig(cfg));
        } else {
            cc.setSslConfig(new SslConfig());
        }
        if (l.getSaslMechanism() != null) {
            final BindConnectionInitializer bc = new BindConnectionInitializer();
            final SaslConfig sc;
            switch (l.getSaslMechanism()) {
                case DIGEST_MD5:
                    sc = new DigestMd5Config();
                    ((DigestMd5Config) sc).setRealm(l.getSaslRealm());
                    break;
                case CRAM_MD5:
                    sc = new CramMd5Config();
                    break;
                case EXTERNAL:
                    sc = new ExternalConfig();
                    break;
                case GSSAPI:
                    sc = new GssApiConfig();
                    ((GssApiConfig) sc).setRealm(l.getSaslRealm());
                    break;
                default:
                    throw new IllegalArgumentException("Unknown SASL mechanism " + l.getSaslMechanism().name());
            }
            sc.setAuthorizationId(l.getSaslAuthorizationId());
            sc.setMutualAuthentication(l.getSaslMutualAuth());
            sc.setQualityOfProtection(l.getSaslQualityOfProtection());
            sc.setSecurityStrength(l.getSaslSecurityStrength());
            bc.setBindSaslConfig(sc);
            cc.setConnectionInitializer(bc);
        } else if (CommonHelper.areEquals(l.getBindCredential(), "*") && CommonHelper.areEquals(l.getBindDn(), "*")) {
            cc.setConnectionInitializer(new FastBindOperation.FastBindConnectionInitializer());
        } else if (CommonHelper.isNotBlank(l.getBindDn()) && CommonHelper.isNotBlank(l.getBindCredential())) {
            cc.setConnectionInitializer(new BindConnectionInitializer(l.getBindDn(), new Credential(l.getBindCredential())));
        }
        return cc;
    }
399646
public static boolean isH2Connection(Settings configuration) {
        final String connStr;
        try {
            connStr = configuration.getConnectionString(
                    Settings.KEYS.DB_CONNECTION_STRING,
                    Settings.KEYS.DB_FILE_NAME);
        } catch (IOException ex) {
            LOGGER.debug("Unable to get connectionn string", ex);
            return false;
        }
        return connStr.startsWith("jdbc:h2:file:");
    }
477947
public static LdapHelper getInstance(String instance) {
        if (!helpers.containsKey(instance)) {
            helpers.put(instance, new LdapHelper(instance));
        }
        LdapHelper helper = helpers.get(instance);
        if (!helper.online) {
            helper.loadProperties();
        }
        return helper;
    }
1257764
public static ConnectionPool newBlockingConnectionPool(final AbstractLdapProperties l) {
        final DefaultConnectionFactory bindCf = newConnectionFactory(l);
        final PoolConfig pc = newPoolConfig(l);
        final BlockingConnectionPool cp = new BlockingConnectionPool(pc, bindCf);

        cp.setBlockWaitTime(newDuration(l.getBlockWaitTime()));
        cp.setPoolConfig(pc);

        final IdlePruneStrategy strategy = new IdlePruneStrategy();
        strategy.setIdleTime(newDuration(l.getIdleTime()));
        strategy.setPrunePeriod(newDuration(l.getPrunePeriod()));

        cp.setPruneStrategy(strategy);
        cp.setValidator(new SearchValidator());
        cp.setFailFastInitialize(l.isFailFast());

        if (CommonHelper.isNotBlank(l.getPoolPassivator())) {
            final AbstractLdapProperties.LdapConnectionPoolPassivator pass =
                    AbstractLdapProperties.LdapConnectionPoolPassivator.valueOf(l.getPoolPassivator().toUpperCase());
            switch (pass) {
                case CLOSE:
                    cp.setPassivator(new ClosePassivator());
                    break;
                case BIND:
                    LOGGER.debug("Creating a bind passivator instance for the connection pool");
                    final BindRequest bindRequest = new BindRequest();
                    bindRequest.setDn(l.getBindDn());
                    bindRequest.setCredential(new Credential(l.getBindCredential()));
                    cp.setPassivator(new BindPassivator(bindRequest));
                    break;
                default:
                    break;
            }
        }

        LOGGER.debug("Initializing ldap connection pool for {} and bindDn {}", l.getLdapUrl(), l.getBindDn());
        cp.initialize();
        return cp;
    }
224877
public Configuration getConfiguration() {
		final Configuration conf = new Configuration();
		for (Map.Entry<String, String> entry : data.entrySet()) {
			conf.setString(entry.getKey(), entry.getValue());
		}
		return conf;
	}
939207
public static SqlConfig getConfig(final String dataSourceName) {
		DataSourceConnectionSupplierImpl connectionSupplier = new DataSourceConnectionSupplierImpl(dataSourceName);
		return new DefaultSqlConfig(connectionSupplier, null);
	}
1309202
public Connection getConnection() throws SQLException {
        try {
            return new DrizzleConnection(new MySQLProtocol(hostname, port, database, null, null, new Properties()),
                    new DrizzleQueryFactory());
        } catch (QueryException e) {
            throw SQLExceptionMapper.get(e);
        }
    }
1084959
private Connection newConnection() throws Exception
   {
      final long start = currentTime();

      Connection connection = null;
      try {
         String username = config.getUsername();
         String password = config.getPassword();

         connection = (username == null) ? dataSource.getConnection() : dataSource.getConnection(username, password);

         setupConnection(connection);
         lastConnectionFailure.set(null);
         return connection;
      }
      catch (Exception e) {
         if (connection != null) {
            quietlyCloseConnection(connection, "(Failed to create/setup connection)");
         }
         else if (getLastConnectionFailure() == null) {
            logger.debug("{} - Failed to create/setup connection: {}", poolName, e.getMessage());
         }

         lastConnectionFailure.set(e);
         throw e;
      }
      finally {
         // tracker will be null during failFast check
         if (metricsTracker != null) {
            metricsTracker.recordConnectionCreated(elapsedMillis(start));
         }
      }
   }
1000941
private ServerConnector configureConnector() {
        ServerConnector connector = null;
        if (m_tls) {
            connector = createSSLConnector();
        } else {
            // Unsecured connector
            connector = new ServerConnector(m_jettyServer);
        }
        if (m_restaddr != null) {
            connector.setHost(m_restaddr);
        }
        connector.setPort(m_restport);
        connector.setIdleTimeout(SOCKET_TIMEOUT_MILLIS);
        connector.addBean(new ConnListener());  // invokes registered callbacks, if any
        return connector;
    }
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))
747952
def _connect(**kwargs):
    '''
    
    '''
    connargs = {}
    for name in ['uri', 'server', 'port', 'tls', 'no_verify', 'binddn',
                 'bindpw', 'anonymous']:
        connargs[name] = _config(name, **kwargs)

    return _LDAPConnection(**connargs).ldap
592050
public static GatewayConfigTranslatorFactory newInstance(ClassLoader cl) {
        ServiceLoader<GatewayConfigTranslatorFactorySpi> services = load(GatewayConfigTranslatorFactorySpi.class, cl);
        return newInstance(services);
    }
562857
public static Connection newInstance(Connection conn) {
        return (Connection) java.lang.reflect.Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[]{Connection.class},
                new ConnectionProxy(conn));
        /*
        return (Connection) java.lang.reflect.Proxy.newProxyInstance(conn.getClass().getClassLoader(), conn.getClass().getInterfaces(),
                new ConnectionProxy(conn));
                */
    }
336723
def _ldap_connection_factory(self, config):
        
        ldap_url = config['ldap_url']
        bind_dn = config['bind_dn']
        bind_password = config['bind_password']

        if not ldap_url:
            raise LdapAttributeStoreError("ldap_url is not configured")
        if not bind_dn:
            raise LdapAttributeStoreError("bind_dn is not configured")
        if not bind_password:
            raise LdapAttributeStoreError("bind_password is not configured")

        pool_size = config['pool_size']
        pool_keepalive = config['pool_keepalive']

        server = ldap3.Server(config['ldap_url'])

        satosa_logging(logger, logging.DEBUG, "Creating a new LDAP connection", None)
        satosa_logging(logger, logging.DEBUG, "Using LDAP URL {}".format(ldap_url), None)
        satosa_logging(logger, logging.DEBUG, "Using bind DN {}".format(bind_dn), None)
        satosa_logging(logger, logging.DEBUG, "Using pool size {}".format(pool_size), None)
        satosa_logging(logger, logging.DEBUG, "Using pool keep alive {}".format(pool_keepalive), None)

        try:
            connection = ldap3.Connection(
                            server,
                            bind_dn,
                            bind_password,
                            auto_bind=True,
                            client_strategy=ldap3.REUSABLE,
                            pool_size=pool_size,
                            pool_keepalive=pool_keepalive
                            )

        except LDAPException as e:
            msg = "Caught exception when connecting to LDAP server: {}".format(e)
            satosa_logging(logger, logging.ERROR, msg, None)
            raise LdapAttributeStoreError(msg)

        satosa_logging(logger, logging.DEBUG, "Successfully connected to LDAP server", None)

        return connection
797032
public Configuration createConfiguration()
    {
        if (crackingHardwareCost == null)
        {
            crackingHardwareCost = getDefaultCrackingHardwareCost();
        }
        if (passwordMatchers == null)
        {
            passwordMatchers = getDefaultPasswordMatchers();
        }
        if (guessTypes == null)
        {
            guessTypes = getDefaultGuessTypes(crackingHardwareCost);
        }
        if (dictionaries == null)
        {
            dictionaries = getDefaultDictionaries();
        }
        if (adjacencyGraphs == null)
        {
            adjacencyGraphs = getDefaultAdjacencyGraphs();
        }
        if (leetTable == null)
        {
            leetTable = getDefaultLeetTable();
        }
        if (yearPattern == null)
        {
            yearPattern = getDefaultYearPattern();
        }
        if (minimumEntropy == null)
        {
            minimumEntropy = getDefaultMinimumEntropy();
        }
        if (locale == null)
        {
            locale = Locale.getDefault();
        }
        if (distanceCalc == null)
        {
            distanceCalc = getDefaultDistanceCalc();
        }
        if (combinationAlgorithmTimeout == null)
        {
            combinationAlgorithmTimeout = getDefaultCombinationAlgorithmTimeout();
        }
        return new Configuration(passwordMatchers, guessTypes, dictionaries, adjacencyGraphs, leetTable, yearPattern, minimumEntropy, locale, distanceCalc, combinationAlgorithmTimeout);
    }
260432
static Map<String, JDBConnection> connectionMapFromConfig(Config config) throws InitializationException {

      final Config globalPropertyConfig;
      if(config.hasPath("acp.property")) {
         globalPropertyConfig = config.getObject("acp.property").toConfig();
      } else if(config.hasPath("property")) {
         globalPropertyConfig = config.getObject("property").toConfig();
      } else {
         globalPropertyConfig = null;
      }


      final Config connectionsConfig;
      if(config.hasPath("acp.connection")) {
         connectionsConfig = config.getObject("acp.connection").toConfig();
      } else if(config.hasPath("connection")) {
         connectionsConfig = config.getObject("connection").toConfig();
      } else {
         return Collections.emptyMap();
      }

      Map<String, JDBConnection> connectionMap = Maps.newLinkedHashMap();

      for(String connectionName : uniquePrefixSet(connectionsConfig)) {
         Config connectionConfig = connectionsConfig.getObject(connectionName).toConfig();
         connectionMap.put(connectionName, createConnection(connectionName, connectionConfig, globalPropertyConfig));
      }

      return connectionMap;
   }
1028708
public Connection getConnection() throws IOException {
		Connection conn = null;
		if (this.datasource != null) {
			try {
				conn = this.datasource.getConnection();
			} catch (SQLException e) {
				throw new IOException(e);
			}
		}
		return conn;
	}