/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.fw.util;

// Java classes
import java.util.HashMap;

import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.util.builder.BuilderException;

/**
 * An exception handler factory that contains a list of exception handlers
 * registered to handle specific exceptions. An exception handler is registered
 * to handle an exception through a map property "handlers" with the key being
 * an exception name and a value being an exception handler itself.
 * 
 * @author Vu Le
 * @version 1.0
 */
public class ExceptionHandlerFactory extends AbstractComponent {

	private HashMap handlers = null;
	private GenericExceptionHandler defaultHandler = null;

	public ExceptionHandlerFactory() {
		super();
	}

	/**
	 * Checks if a message map is set correctly
	 * 
	 * @throws BuilderException
	 *             Thrown if a message map is not set
	 */
	public void afterPropertiesSet() throws Exception {
		if (defaultHandler == null) {
			// If a default handler is not specified, provide one here
			defaultHandler = new GenericExceptionHandler();
		}
	}

	/**
	 * @return Returns the handlers.
	 */
	public HashMap getHandlers() {
		return handlers;
	}

	/**
	 * @param handlers
	 *            The handlers to set.
	 */
	public void setHandlers(HashMap handlers) {
		this.handlers = handlers;
	}

	/**
	 * @return Returns the defaultHandler.
	 */
	public GenericExceptionHandler getDefaultHandler() {
		return defaultHandler;
	}

	/**
	 * @param defaultHandler
	 *            The defaultHandler to set.
	 */
	public void setDefaultHandler(GenericExceptionHandler defaultHandler) {
		this.defaultHandler = defaultHandler;
	}

	/**
	 * Returns an exception handler for specific exception
	 * 
	 * @param exceptionName
	 *            An exeption name
	 * @return ExceptionHandler
	 */
	public ExceptionHandler getExceptionHandler(String exceptionName) {

		if (exceptionName == null) {
			throw new IllegalArgumentException("Invalid exception name. Name = " + exceptionName);
		}

		Object handler = null;

		// If a map of handlers are not configured to register specific handlers
		// to handle specific exceptions, use a default handler instead
		if (handlers != null) {
			handler = handlers.get(exceptionName);
		}
		return ((handler == null || !(handler instanceof ExceptionHandler) ? defaultHandler
				: (ExceptionHandler) handler));
	}
}