protected synchronized void initDataSource()

in jee-modules/jpa-module/impl/src/main/java/org/apache/myfaces/extensions/cdi/jpa/impl/datasource/ConfigurableDataSource.java [184:260]


    protected synchronized void initDataSource() throws SQLException
    {
        // double check lock idiom on volatile member is ok as of Java5
        if (loaded)
        {
            return;
        }
        loaded = true;

        String jndiLookupName = dataSourceConfig.getJndiResourceName(connectionId);
        if (jndiLookupName != null && jndiLookupName.length() > 0)
        {
            wrappedDataSource = JndiUtils.lookup(jndiLookupName, DataSource.class);
            return;
        }

        // no JNDI, so we take the direct JDBC route.
        String dataSourceClass = dataSourceConfig.getConnectionClassName(connectionId);

        if (dataSourceClass == null || dataSourceClass.length() == 0)
        {
            throw new SQLException("Neither a JNDI location nor a JDBC driver class name is configured!");
        }

        connectionProperties = dataSourceConfig.getConnectionProperties(connectionId);

        try
        {
            // we explicitely use class.forName and NOT the ThreadContextClassLoader!
            Class clazz =  Class.forName(dataSourceClass);

            // the given driver classname must be a DataSource
            if (DataSource.class.isAssignableFrom(clazz))
            {
                wrappedDataSource = (DataSource) clazz.newInstance();

                for (Map.Entry configOption : connectionProperties.entrySet())
                {
                    String name = (String) configOption.getKey();
                    String value = (String) configOption.getValue();
                    setProperty(wrappedDataSource, name, value);
                }
            }
            else if(Driver.class.isAssignableFrom(clazz))
            {
                // if we have a javax.sql.Driver then we also need an explicite connection URL
                jdbcConnectionURL = dataSourceConfig.getJdbcConnectionUrl(connectionId);
                if (jdbcConnectionURL == null)
                {
                    throw new SQLException("Neither a JNDI location nor a JDBC connection URL is configured!");
                }

                wrappedJdbcDriver = (Driver) clazz.newInstance();
            }
            else
            {
                throw new SQLException("Configured DriverClassName is not a javax.sql.DataSource "
                                       + "nor a javax.sql.Driver: "
                                       + dataSourceClass);
            }
        }
        catch (RuntimeException e)
        {
            wrappedDataSource = null;
            throw e;
        }
        catch (SQLException e)
        {
            wrappedDataSource = null;
            throw e;
        }
        catch (Exception e)
        {
            wrappedDataSource = null;
            throw new RuntimeException(e);
        }
    }