/***************************************************************************
 *   Copyright (C) by Fabrizio Montesi                                     *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 *                                                                         *
 *   For details about the authors of this software, see the AUTHORS file. *
 ***************************************************************************/

package jolie.process;

import jolie.ExecutionThread;
import jolie.runtime.FaultException;
import jolie.runtime.VariablePath;

public class ForEachProcess implements Process
{
	final private VariablePath keyPath, targetPath;
	final private Process process;

	public ForEachProcess(
			VariablePath keyPath,
			VariablePath targetPath,
			Process process )
	{
		this.keyPath = keyPath;
		this.targetPath = targetPath;
		this.process = process;
	}
	
	public Process clone( TransformationReason reason )
	{
		return new ForEachProcess(
					(VariablePath) keyPath.cloneExpression( reason ),
					(VariablePath) targetPath.cloneExpression( reason ),
					process.clone( reason )
				);
	}
	
	public void run()
		throws FaultException
	{
		if ( ExecutionThread.currentThread().isKilled() )
			return;
		
		for( String id : targetPath.getValue().children().keySet() ) {
			keyPath.getValue().setValue( id );
			process.run();
		}
	}
	
	public boolean isKillable()
	{
		return true;
	}
}

@@ -1626,16 +1626,44 @@
 eption;%0A
+import jolie.runtime.Value;%0A
 import j
@@ -2361,17 +2361,77 @@
 turn;%0A%09%09
-%0A
+Value v = targetPath.getValue();%0A%09%09if ( v.hasChildren() ) %7B%0A%09
 %09%09for( S
@@ -2490,16 +2490,17 @@
  ) %7B%0A%09%09%09
+%09
 keyPath.
@@ -2529,16 +2529,17 @@
 d );%0A%09%09%09
+%09
 process.
@@ -2545,16 +2545,21 @@
 .run();%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%09%7D%0A%09

Check if the target has children before entering a foreach loop.