/*
 * [ConnectJDBCDataSource.java]
 *
 * Summary: demonstrate the how to connect to a database via a DataSource.
 *
 * Copyright: (c) 2011-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2011-02-22 initial version
 */
package com.mindprod.example;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * demonstrate the how to connect to a database via a DataSource.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2011-02-22 initial version
 * @since 2011-02-22
 */
public class ConnectJDBCDataSource
    {
    /**
     * which database
     */
    private static final String DATA_BASE_NAME = "squirrels";
    // no driver, user name or password required.

    /**
     * The connection.  Handle to the database
     */
    private static Connection conn;

    /**
     * connect to the database in the new "improved" way that requires five extra lines of meaningless bubblegum.
     */
    private static Connection connect() throws NamingException, SQLException
        {
        // These two calls are not normally needed. They are handled
        // for you by the servlet womb.
        System.setProperty( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" );
        System.setProperty( Context.PROVIDER_URL, "file:///tmp" );
        // accessing a database in TomCat using a DataSource.
        // Obtain environment naming context
        final Context initialContext = new InitialContext();
        final Context envContext = ( Context ) initialContext.lookup( "java:comp/env" );
        // Look up the data source, which knows the user/password/url/jdbc drivers etc.
        final DataSource ds = ( DataSource ) envContext.lookup( "jdbc/" + DATA_BASE_NAME );
        // Allocate and use a connection from the pool
        return ds.getConnection();
        }

    /**
     * initialise the database
     *
     * @param args not used
     */
    public static void main( String[] args ) throws NamingException, SQLException
        {
        conn = connect();
        // ...
        conn.close();
        }
    }