/**
 * MessageHandlerFactory is a class that creates MessageHandler subtypes
 * based on the first line of a message.  This factory uses the Chain of
 * Responsibility pattern to determine which subtype should be
 * instantiated.
 * <br>
 * This source code is copyright 2005 by Patrick May.  All
 * rights reserved.
 *
 * @author Patrick May (patrick@softwarematters.org)
 * @author &copy; 2005 Patrick May.  All rights reserved.
 * @version 1
 */

package org.softwarematters.example.MessageBroker;

import java.util.logging.Logger;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.lang.reflect.Constructor;

public class MessageHandlerFactory
{
  private static Logger logger_
    = Logger.getLogger(MessageHandlerFactory.class.getName());

  private Set<Class> handlers_ = new HashSet<Class>();

  /**
   * The default constructor for the MessageHandlerFactory class.
   */
  public MessageHandlerFactory()
    {
    }


  /**
   * Add the specified class name to the list of handlers.
   *
   * @param handlerName The name of the MessageHandler subtype to add.
   */
  public void addHandler(String handlerName) throws ClassNotFoundException
    {
    Class handlerClass = null;
    try
      {
      handlerClass = Class.forName(handlerName);
      handlers_.add(handlerClass);
      }
    catch (Exception e)
      {
      throw new ClassNotFoundException(handlerName);
      }
    }


  /**
   * Create a new MessageHandler subtype based on the specified message.
   *
   * @param message The message to be handled.
   */
  public MessageHandler getMessageHandler(String message)
    {
    MessageHandler handler = null;
    Constructor ctor = null;
    Iterator it = handlers_.iterator();

    while(it.hasNext() && (handler == null))
      {
      try
        {
        ctor = ((Class)it.next()).getConstructor(String.class);
        try
          {
          handler = (MessageHandler)ctor.newInstance(message);
          }
        catch (Exception e)
          {
          handler = null;
          logger_.info(e.toString());
          }
        }
      catch (NoSuchMethodException nsm)
        {
        logger_.warning("Bad handler found:  " + nsm.toString());
        }
      }

    return handler;
    }


  /**
   * A test harness for the MessageHandlerFactory class.
   *
   * @param args The command line arguments passed in.
   */
  public static void main(String args[])
    {
    }
}  // end MessageHandlerFactory

