//----------------------------BEGIN LICENSE----------------------------
/* 
 * Willow : the Open Source WorkFlow Project
 * Distributable under GNU LGPL license by gun.org
 *
 * Copyright (C) 2004-2010  huihoo.org 
 * Copyright (C) 2004-2010  ZosaTapo <dertyang@hotmail.com> 
 * 
 * ====================================================================
 * Project Homepage : http://www.huihoo.org/willow
 * Source Forge     : http://sourceforge.net/projects/huihoo
 * Mailing list     : willow@lists.sourceforge.net 
 */
//----------------------------END  LICENSE----------------------------
package org.huihoo.willow.tomcat;

import java.lang.reflect.Method;

import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
import org.huihoo.willow.desktop.WorkflowDesktopFactoryImpl;
import org.huihoo.workflow.desktop.WorkflowDesktop;

public class CatalinaHostLifecycleListener implements LifecycleListener
{
	/**
		 * Process the AFTER_START_EVENT event for an associated Context.
		 *
		 * @param event The lifecycle event that has occurred
		 */
	public void lifecycleEvent(LifecycleEvent event)
	{
		if (event.getType().equals(Lifecycle.AFTER_START_EVENT))
		{
			try
			{
				afterStart(event.getLifecycle());
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}

	}
	
	/**
	 * Process a "start" event for this Host - in background
	 */
	private synchronized void afterStart(Object host)
	throws Exception 
	{
		Method method = null;
		
		method = host.getClass().getMethod("findChildren", null);
		Object[] contexts=(Object[])method.invoke(host, null);

		if(contexts==null)
		{
			return;
		}

		for(int k=0;k<contexts.length;++k)
		{
			Object context=contexts[k];
			method = context.getClass().getMethod("getServletContext", null);
			Object servletContext=method.invoke(context,null);

			Class paramTypes[] = {String.class,Object.class};
			Object paramValues[] = new Object[2];
			paramValues[0]=WorkflowDesktop.INITIAL_DESKTOP_FACTORY;
			paramValues[1]=new WorkflowDesktopFactoryImpl();

			method = servletContext.getClass().getMethod("setAttribute", paramTypes);
			method.invoke(servletContext,paramValues);
		}
	}
}
