//----------------------------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.workflow;

import java.util.List;

import org.huihoo.workflow.xpdl.ExtendedAttribute;
import org.huihoo.workflow.xpdl.WorkflowActivity;
import org.huihoo.workflow.xpdl.WorkflowProcess;
import org.huihoo.workflow.xpdl.WorkflowTransition;
import org.huihoo.workflow.xpdl.XPDLGlobals;

public class WorkflowUtilities
{
	public static WorkflowActivity getInitialActivity(WorkflowProcess workflowProcess)
	{
		WorkflowActivity beginActivity = getBeginActivity(workflowProcess);
		
		if(beginActivity == null)
		{
			return null;
		}
		
		List outTrans = beginActivity.getValidOutgoingTransitions();
		WorkflowTransition firstTransition = (WorkflowTransition) outTrans.get(0);

		return  firstTransition.getToActivity();
	}

	public static WorkflowActivity getBeginActivity(WorkflowProcess workflowProcess)
	{
		ExtendedAttribute attribute =
			(ExtendedAttribute) workflowProcess.findExtendedAttribute(XPDLGlobals.ID_ACTIVITY_BEGIN);

		if (attribute == null)
		{
			return null;
		}

		String beginActivityId = attribute.getValue();
		return workflowProcess.findActivity(beginActivityId);
	}

	public static WorkflowActivity getEndActivity(WorkflowProcess workflowProcess)
	{
		ExtendedAttribute attribute =
			(ExtendedAttribute) workflowProcess.findExtendedAttribute(XPDLGlobals.ID_ACTIVITY_END);

		if (attribute == null)
		{
			return null;
		}

		String endActivityId = attribute.getValue();
		return workflowProcess.findActivity(endActivityId);
	}
	
	public static void releaseNoThrow(WorkflowTransaction transaction)
	{

		try
		{
			if (transaction != null)
			{
				transaction.release();
			}
		}
		catch (TransactionException e)
		{
			;
		}
	}

	public static void releaseThrow(WorkflowTransaction transaction) throws WorkflowException
	{
		if (transaction != null)
		{
			transaction.release();
		}
	}

	public static void rollbackNoThrow(WorkflowTransaction transaction)
	{

		try
		{
			if (transaction != null)
			{
				transaction.rollback();
			}
		}
		catch (TransactionException e)
		{
			;
		}
	}
}
