

package gov.va.med.cds.persistence;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Required;

import java.util.ArrayList;
import java.util.Collection;

import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.sql.DataSource;


/**
 * This class locates all of the JNDI data source bindings whose name matches 
 * the specified pattern.
 * @author DNS   roberk
 *
 */
public class JNDIDataSourceBindingsLocator
    implements
        JNDIDataSourceBindingsLocatorInterface
{

    private Log logger = LogFactory.getLog( JNDIDataSourceBindingsLocator.class );

    private Context initialContext;
    private String namedContext = "";// The initial context


    /*   public void init( )
           throws NamingException
       {
           // Create a Properties object and set properties appropriately
           Properties props = new Properties();
           props.put( Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory" );

           // Create the initial context from the properties we just created
           this.initialContext = new InitialContext( props );
       }*/

    /**
     * Gets the collection of JNDI data source bindings that match the
     * specified pattern.
     */
    @Override
    public Collection<Binding> getDataSourceBindings( )
    {
        Collection<Binding> result = new ArrayList<Binding>();
        try
        {

            // Get the JNDI bindings
            NamingEnumeration<Binding> enumeration = initialContext.listBindings( this.namedContext );
            try
            {
                while ( enumeration.hasMore() )
                {
                    Binding binding = enumeration.next();
                    Object obj = binding.getObject();
                    // This locator only cares about javax.sql.DataSource objects.
                    if ( obj instanceof DataSource )
                    {
                        result.add( binding );
                    }
                }
            }
            catch ( NamingException ex )
            {
                throw new RuntimeException( getClass().getName() + " could not retrieve all data source bindings", ex );
            }
            finally
            {
                enumeration.close();
            }
        }
        catch ( NamingException nnfe )
        {
            if ( logger.isDebugEnabled() )
            {
                logger.debug( gov.va.med.cds.util.LogMessageUtil.buildMessage( null, null, null,
                                String.format( "%s: No data source bindings matching '%s'.", getClass().getName(), this.namedContext ) ) );

            }

        }
        if ( logger.isInfoEnabled() )
        {
            String msg = "Located " + result.size() + " site specific data source bindings in context " + this.namedContext;

            logger.info( gov.va.med.cds.util.LogMessageUtil.buildMessage( null, null, null, msg ), null );

        }
        return result;
    }


    /**
     * Sets the namedContext that is passed into the 
     * JNDI InitialContext.listBinding() method. If not 
     * specified, the initial context is used.
     * @param namedContext - The name of the JNDI context to search.
     */
    public void setNamedContext( String namedContext )
    {
        this.namedContext = namedContext;
    }


    /**
     * Sets the JNDI initial context.
     * @param initialContext - the initial context instance.
     */

    @Required
    public void setInitialContext( Context initialContext )
    {
        this.initialContext = initialContext;
    }
}
