Will create and return either a {@link SimpleDataSource} or a {@link PoolingDataSource}
depending on the presence in the supplied properties of any pool-related property (eg.: {@code
JDBC_INITIAL_POOL_SIZE} or {@code JDBC_MAX_POOL_SIZE}).
518769
public DataSource createDataSource(Properties props) throws SQLException {
    props = new SingleUseProperties(props);
    if (props.containsKey(JDBC_INITIAL_POOL_SIZE)
        || props.containsKey(JDBC_MIN_POOL_SIZE)
        || props.containsKey(JDBC_MAX_POOL_SIZE)
        || props.containsKey(JDBC_MAX_IDLE_TIME)
        || props.containsKey(JDBC_MAX_STATEMENTS)) {
      return createPoolingDataSource(props);
    } else {
      return createSimpleDataSource(props);
    }
  }
292531
@Override
    public Object createResource(ResourceInfo info) throws Exception {
        ComponentMetaData cData = ComponentMetaDataAccessorImpl.getComponentMetaDataAccessor().getComponentMetaData();
        if (cData != null)
            applications.add(cData.getJ2EEName().getApplication());

        return cloudantSvc.createResource(
                                          (String) props.get("databaseName"),
                                          (Boolean) props.get("create"),
                                          info == null ? ResourceInfo.AUTH_APPLICATION : info.getAuth(),
                                          info == null ? null : info.getLoginPropertyList());
    }
202424
public static DataSource createDataSource(String source, String jndiName){
		DataSource ds = createDataSource(source);
		if (ds != null && jndiName != null){
			InitialContext ic;
			try {
				ic = new InitialContext();
				ic.bind(jndiName, ds);
			} catch (NamingException e) {
				log.error("Failed to bind data source '" + source + "' to JNDI name: " + jndiName, e);
			}
		}
		return ds;
	}
568254
@Nonnull
	private static DataSource createDataSource(@Nonnull final MimePart part) {
		final DataHandler dataHandler = retrieveDataHandler(part);
		final DataSource dataSource = dataHandler.getDataSource();
		final String contentType = parseBaseMimeType(dataSource.getContentType());
		final byte[] content = readContent(retrieveInputStream(dataSource));
		final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType);
		final String dataSourceName = parseDataSourceName(part, dataSource);

		result.setName(dataSourceName);
		return result;
	}
1277626
@Override
  public PooledExecutionServiceConfiguration build() {
    PooledExecutionServiceConfiguration config = new PooledExecutionServiceConfiguration();
    if (defaultPool != null) {
      config.addDefaultPool(defaultPool.alias, defaultPool.minSize, defaultPool.maxSize);
    }
    for (Pool pool : pools) {
      config.addPool(pool.alias, pool.minSize, pool.maxSize);
    }
    return config;
  }
558108
public static <S extends ScopeType<S>> BasicDataSource get(Config config,
      SharedResourcesBroker<S> broker) throws IOException {
    try {
      return broker.getSharedResource(new MysqlDataSourceFactory<S>(),
          new MysqlDataSourceKey(MysqlStateStore.getDataSourceId(config), config));
    } catch (NotConfiguredException nce) {
      throw new IOException(nce);
    }
  }
71552
@SuppressWarnings("unchecked")
    protected <T extends RepositoryResourceImpl> T createNewResource() {

        T result;
        if (null == getType()) {
            result = (T) createTestResource(getRepositoryConnection());
        } else {
            result = ResourceFactory.getInstance().createResource(getType(), getRepositoryConnection(), null);
        }
        return result;
    }
1153569
private void initDatasource()  {
		if(this.isIncreamentImport()) {
			if(this.esjdbc.getStatusDbConfig() == null) {
				statusDbname = this.esjdbc.getDbConfig().getDbName() + "_config";
				String dbJNDIName = this.esjdbc.getDbConfig().getDbName() + "_config";
				try {
					createStatusTableSQL = new StringBuilder().append("create table " ).append( statusTableName)
							.append( " (ID number(10),lasttime number(10),lastvalue number(10),lastvaluetype number(1),PRIMARY KEY (ID))").toString();
					File dbpath = new File(statusStorePath);
					logger.info("initDatasource dbpath:" + dbpath.getCanonicalPath());
					SQLUtil.startPool(statusDbname,
							"org.sqlite.JDBC",
							"jdbc:sqlite://" + dbpath.getCanonicalPath(),
							"root", "root",
							null,//"false",
							null,// "READ_UNCOMMITTED",
							"select 1",
							dbJNDIName,
							10,
							10,
							20,
							true,
							false,
							null, false, false
					);
				} catch (Exception e) {
					throw new ESDataImportException(e);
				}
			}
			else{
				DBConfig statusDBConfig = esjdbc.getStatusDbConfig();

				statusDbname = esjdbc.getStatusDbConfig().getDbName();
				if(!statusDbname.equals(esjdbc.getDbConfig().getDbName())){
					String dbJNDIName = statusDbname + "_config";
					try {

						SQLUtil.startPool(statusDbname,
								statusDBConfig.getDbDriver(),
								statusDBConfig.getDbUrl(),
								statusDBConfig.getDbUser(), statusDBConfig.getDbPassword(),
								null,//"false",
								null,// "READ_UNCOMMITTED",
								statusDBConfig.getValidateSQL(),
								dbJNDIName,
								10,
								10,
								20,
								true,
								false,
								null, false, false
						);
					} catch (Exception e) {
						throw new ESDataImportException(e);
					}
				}
				createStatusTableSQL = statusDBConfig.getStatusTableDML();
				if(createStatusTableSQL == null){
					createStatusTableSQL = statusDBConfig.getCreateStatusTableSQL(SQLUtil.getPool(statusDbname).getDBType());
				}
				createStatusTableSQL = createStatusTableSQL.replace("$statusTableName",statusTableName);
			}

			if (esjdbc.getDateLastValueColumn() != null) {
				this.lastValueType = ImportIncreamentConfig.TIMESTAMP_TYPE;
			} else if (esjdbc.getNumberLastValueColumn() != null) {
				this.lastValueType = ImportIncreamentConfig.NUMBER_TYPE;

			} else if (esjdbc.getLastValueType() != null) {
				this.lastValueType = esjdbc.getLastValueType();
			} else {
				this.lastValueType = ImportIncreamentConfig.NUMBER_TYPE;
			}


			existSQL = new StringBuilder().append("select 1 from ").append(statusTableName).toString();
			selectSQL = new StringBuilder().append("select id,lasttime,lastvalue,lastvaluetype from ")
					.append(statusTableName).append(" where id=?").toString();
			updateSQL = new StringBuilder().append("update ").append(statusTableName)
					.append(" set lasttime = ?,lastvalue = ? ,lastvaluetype= ? where id=?").toString();
			insertSQL = new StringBuilder().append("insert into ").append(statusTableName)
					.append(" (id,lasttime,lastvalue,lastvaluetype) values(?,?,?,?)").toString();
		}
	}
284990
public ResponseBuilder createResource() {
        final String baseUrl = getBaseUrl();
        final String identifier = baseUrl + req.getPartition() + req.getPath() + id;
        final String contentType = req.getContentType();
        final Session session = ofNullable(req.getSession()).orElseGet(HttpSession::new);

        LOGGER.info("Creating resource as {}", identifier);

        final Optional<RDFSyntax> rdfSyntax = ofNullable(contentType).flatMap(RDFSyntax::byMediaType)
            .filter(SUPPORTED_RDF_TYPES::contains);

        final IRI defaultType = nonNull(contentType) && !rdfSyntax.isPresent() ? LDP.NonRDFSource : LDP.RDFSource;
        final IRI internalId = rdf.createIRI(TRELLIS_PREFIX + req.getPartition() + req.getPath() + id);

        // Add LDP type (ldp:Resource results in the defaultType)
        final IRI ldpType = ofNullable(req.getLink())
            .filter(l -> "type".equals(l.getRel())).map(Link::getUri).map(URI::toString)
            .filter(l -> l.startsWith(LDP.URI)).map(rdf::createIRI)
            .filter(l -> !LDP.Resource.equals(l)).orElse(defaultType);

        if (ldpType.equals(LDP.NonRDFSource) && rdfSyntax.isPresent()) {
            return status(BAD_REQUEST).type(TEXT_PLAIN).entity("Cannot save a NonRDFSource with RDF syntax");
        }

        try (final TrellisDataset dataset = TrellisDataset.createDataset()) {

            // Add Audit quads
            audit.ifPresent(svc ->
                    svc.creation(internalId, session).stream().map(skolemizeQuads(resourceService, baseUrl))
                .forEachOrdered(dataset::add));

            dataset.add(rdf.createQuad(PreferServerManaged, internalId, RDF.type, ldpType));

            // Add user-supplied data
            if (ldpType.equals(LDP.NonRDFSource)) {
                // Check the expected digest value
                final Digest digest = req.getDigest();
                if (nonNull(digest) && !getDigestForEntity(digest).equals(digest.getDigest())) {
                    return status(BAD_REQUEST);
                }

                final Map<String, String> metadata = singletonMap(CONTENT_TYPE, ofNullable(contentType)
                        .orElse(APPLICATION_OCTET_STREAM));
                final IRI binaryLocation = rdf.createIRI(binaryService.getIdentifierSupplier(req.getPartition())
                        .get());
                dataset.add(rdf.createQuad(PreferServerManaged, internalId, DC.hasPart, binaryLocation));
                dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.modified,
                            rdf.createLiteral(now().toString(), XSD.dateTime)));
                dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.format,
                            rdf.createLiteral(ofNullable(contentType).orElse(APPLICATION_OCTET_STREAM))));
                dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.extent,
                            rdf.createLiteral(Long.toString(entity.length()), XSD.long_)));

                // Persist the content
                persistContent(binaryLocation, metadata);
            } else {
                readEntityIntoDataset(identifier, baseUrl, PreferUserManaged, rdfSyntax.orElse(TURTLE), dataset);

                // Check for any constraints
                checkConstraint(dataset, PreferUserManaged, ldpType, TRELLIS_PREFIX + req.getPartition(),
                        rdfSyntax.orElse(TURTLE));
            }

            if (resourceService.put(internalId, dataset.asDataset())) {
                final ResponseBuilder builder = status(CREATED).location(create(identifier));

                // Add LDP types
                ldpResourceTypes(ldpType).map(IRI::getIRIString).forEach(type -> builder.link(type, "type"));

                return builder;
            }
        }

        LOGGER.error("Unable to persist data to location at {}", internalId.getIRIString());
        return serverError().type(TEXT_PLAIN)
            .entity("Unable to persist data. Please consult the logs for more information");
    }
1252155
DataSource getFastDatasource() {
		if(delegatedDataSource==null){
			delegatedDataSource = dbms.getFastDataSource(this);
			if(delegatedDataSource == null){
				throw new RuntimeException("Unable to obtain datasource from dbms");
			}
		}
		return delegatedDataSource;
	}
1330723
@Override
	public DataSource createDataSource(String source, Properties configurationProperties, String config) {
		DataSource ds = null;
		try {
			DirectDataSourceConfiguration cfg = new DirectDataSourceConfiguration(configurationProperties);
			ds = new DriverManagerDataSource(cfg.getDriverClassName(), cfg.getUrl(), cfg.getConnectionProperties()); 
		} catch (ClassNotFoundException e) {
			log.error("Driver class not found for '" + source + "' with configuration: " + configurationProperties, e);
		} catch (Exception e) {
			log.error("Error creating data source for '" + source + "' with configuration: " + configurationProperties, e);
		}
		return ds;
	}
401882
private static PropertySourceGenerator getSourceGenerator(final ErrorBuffer errorBuffer, final String className, final PropertyDefinition propertyDefinition) throws FrameworkException {

		final String propertyName                                  = propertyDefinition.getPropertyName();
		final Type propertyType                                    = propertyDefinition.getPropertyType();
		final Class<? extends PropertySourceGenerator> parserClass = parserMap.get(propertyType);

		try {

			return parserClass.getConstructor(ErrorBuffer.class, String.class, PropertyDefinition.class).newInstance(errorBuffer, className, propertyDefinition);

		} catch (Throwable t) {
			logger.warn("", t);
		}

		errorBuffer.add(new InvalidPropertySchemaToken(SchemaProperty.class.getSimpleName(), propertyName, propertyName, "invalid_property_definition", "Unknow value type " + source + ", options are " + Arrays.asList(Type.values()) + "."));
		throw new FrameworkException(422, "Invalid property definition for property " + propertyDefinition.getPropertyName(), errorBuffer);
	}
1297632
public ConnectionPoolDataSource createConnectionPoolDataSource(Properties props, String dataSourceID) throws SQLException {
        lock.readLock().lock();
        try {
            if (!isInitialized)
                try {
                    // Switch to write lock for lazy initialization
                    lock.readLock().unlock();
                    lock.writeLock().lock();

                    if (!isInitialized) {
                        if (!loadFromApp())
                            classloader = AdapterUtil.getClassLoaderWithPriv(sharedLib);
                        isInitialized = true;
                    }
                } finally {
                    // Downgrade to read lock for rest of method
                    lock.readLock().lock();
                    lock.writeLock().unlock();
                }

            String className = (String) properties.get(ConnectionPoolDataSource.class.getName());
            if (className == null) {
                String vendorPropertiesPID = props instanceof PropertyService ? ((PropertyService) props).getFactoryPID() : PropertyService.FACTORY_PID;
                className = JDBCDrivers.getConnectionPoolDataSourceClassName(vendorPropertiesPID);
                if (className == null) {
                    //if properties.oracle.ucp is configured do not search based on classname or infer because the customer has indicated
                    //they want to use UCP, but this will likely pick up the Oracle driver instead of the UCP driver (since UCP has no ConnectionPoolDataSource)
                    if("com.ibm.ws.jdbc.dataSource.properties.oracle.ucp".equals(vendorPropertiesPID)) {
                        throw new SQLNonTransientException(AdapterUtil.getNLSMessage("DSRA4015.no.ucp.connection.pool.datasource", dataSourceID, ConnectionPoolDataSource.class.getName()));
                    }
                    className = JDBCDrivers.getConnectionPoolDataSourceClassName(getClasspath(sharedLib, true));
                    if (className == null) {
                        Set<String> packagesSearched = new LinkedHashSet<String>();
                        SimpleEntry<Integer, String> dsEntry = JDBCDrivers.inferDataSourceClassFromDriver //
                                        (classloader, packagesSearched, JDBCDrivers.CONNECTION_POOL_DATA_SOURCE); 
                        className = dsEntry == null ? null : dsEntry.getValue();
                        if (className == null)
                            throw classNotFound(ConnectionPoolDataSource.class.getName(), packagesSearched, dataSourceID, null);
                    }
                }
            }

            return create(className, props, dataSourceID);
        } finally {
            lock.readLock().unlock();
        }
    }
42105
@FFDCIgnore(Exception.class)
    public DataSource getDataSource() throws Exception {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "getDataSource");

        // Retrieve the data source factory from the CustomLogProperties. This Factory should be set in the JTMConfigurationProvider
        // by the jdbc component using DeclarativeServices. TxRecoveryAgentImpl gets the factory from the ConfigurationProvider and
        // then sets it into CustomLogProperties.
        ResourceFactory dataSourceFactory = _customLogProperties.resourceFactory();

        if (dataSourceFactory != null) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Using DataSourceFactory " + dataSourceFactory);
        } else {
            if (tc.isEntryEnabled())
                Tr.exit(tc, "getDataSource", "Null ResourceFactory InternalLogException");
            throw new InternalLogException("Failed to locate DataSource, null Resourcefactory", null);
        }

        try {
            nonTranDataSource = (DataSource) dataSourceFactory.createResource(null);
        } catch (Exception e) {
            //e.printStackTrace();
            if (tc.isEntryEnabled())
                Tr.exit(tc, "getDataSource", "Caught exception " + e + "throw InternalLogException");
            throw new InternalLogException("Failed to locate DataSource, caught exception ", null);
        }

/*
 * TEMPORARY This is waiting on fixes to DeclarativeServices which impact the jdbc component. At present it is
 * possible that the DataSource will have been set but that its associated jdbc driver service will still be initialising
 */
//        boolean refSet = false;
//        while (!refSet)
//        {
//            if (tc.isDebugEnabled())
//                Tr.debug(tc, "getDataSource after sleep");
//            try {
//
//                nonTranDataSource = (DataSource) dataSourceFactory.createResource(null);
//                if (tc.isDebugEnabled())
//                    Tr.debug(tc, "Non Tran dataSource is " + nonTranDataSource);
//                Connection conn = nonTranDataSource.getConnection();
//                if (tc.isDebugEnabled())
//                    Tr.debug(tc, "Established connection " + conn);
//
//                DatabaseMetaData mdata = conn.getMetaData();
//
//                String dbName = mdata.getDatabaseProductName();
//                if (tc.isDebugEnabled())
//                    Tr.debug(tc, "Database name " + dbName);
//
//                String dbVersion = mdata.getDatabaseProductVersion();
//                if (tc.isDebugEnabled())
//                    Tr.debug(tc, "Database version " + dbVersion);
//                refSet = true;
//            } catch (Exception e) {
//                // We will catch an exception if the DataSource is not yet fully formed
//                if (tc.isDebugEnabled())
//                    Tr.debug(tc, "Caught exception: " + e);
//            }
//
//            if (!refSet)
//                Thread.sleep(200);
//        }
// eof TEMPORARY

        if (tc.isEntryEnabled())
            Tr.exit(tc, "getDataSource", nonTranDataSource);
        return nonTranDataSource;
    }
309145
private void createPool(String poolName, Properties connectionPoolProperties) {

    releaseConnectionPool(poolName);

    // DBUtils execute methods require autoCommit to be true.
    connectionPoolProperties.put("autoCommit", true);

    HikariConfig config = new HikariConfig(connectionPoolProperties);
    config.setPoolName(poolName);
    HikariDataSource ds = new HikariDataSource(config);
    pools.put(poolName, ds);
    logger.info("Initialized pool '{}'", poolName);
  }
10186
public static <T> TableSource<T> findAndCreateTableSource(Descriptor descriptor) {
		Map<String, String> properties = descriptor.toProperties();

		TableSource tableSource;
		try {
			tableSource = TableFactoryService
				.find(TableSourceFactory.class, properties)
				.createTableSource(properties);
		} catch (Throwable t) {
			throw new TableException("findAndCreateTableSource failed.", t);
		}

		return tableSource;
	}
1047601
public PropertyType<ConnectionFactoryResourceType<T>> getOrCreateProperty()
   {
      List<Node> nodeList = childNode.get("property");
      if (nodeList != null &&  nodeList.size() > 0)
      {
         return new PropertyTypeImpl<ConnectionFactoryResourceType<T>>(this, "property", childNode, nodeList.get(0));
      }
      return createProperty();
   }