/*
 * Created on Dec 6, 2006
 */
package org.griphyn.vdl.karajan.functions;

import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.globus.cog.karajan.arguments.Arg;
import org.globus.cog.karajan.stack.VariableStack;
import org.globus.cog.karajan.util.TypeUtil;
import org.globus.cog.karajan.workflow.ExecutionException;
import org.globus.cog.karajan.workflow.nodes.functions.AbstractFunction;
import org.griphyn.vdl.karajan.VDL2ErrorTranslator;

public class ProcessBulkErrors extends AbstractFunction {
	public static final Logger logger = Logger.getLogger(ProcessBulkErrors.class);
	
	public static final Arg ERRORS = new Arg.Positional("errors");

	static {
		setArguments(ProcessBulkErrors.class, new Arg[] { ERRORS });
	}

	public Object function(VariableStack stack) throws ExecutionException {
		VDL2ErrorTranslator translator = VDL2ErrorTranslator.getDefault();

		List l = TypeUtil.toList(ERRORS.getValue(stack));
		Map count = new HashMap();
		Iterator i = l.iterator();
		while (i.hasNext()) {
			ExecutionException ex = (ExecutionException) i.next();
			if (ex.getCause() instanceof ConcurrentModificationException) {
				ex.printStackTrace();
			}
			if (logger.isDebugEnabled()) {
				logger.debug(ex);
			}
			String msg = ex.getMessage();
			String tmsg = translator.translate(msg);
			if (tmsg == null) {
				if (msg != null && msg.startsWith("VDL2: ")) {
					tmsg = msg.substring(6);
				}
				else {
					tmsg = ex.toString();
				}
			}
			if (count.containsKey(tmsg)) {
				Integer j = (Integer) count.get(tmsg);
				count.put(tmsg, new Integer(j.intValue() + 1));
			}
			else {
				count.put(tmsg, new Integer(1));
			}
		}
		if (count.size() != 0) {
			STDERR.ret(stack, "The following errors have occurred:\n");
			i = count.entrySet().iterator();
			while (i.hasNext()) {
				Map.Entry e = (Map.Entry) i.next();
				Integer j = (Integer) e.getValue();
				if (j.intValue() == 1) {
					STDERR.ret(stack, e.getKey() + "\n");
				}
				else {
					STDERR.ret(stack, e.getKey() + " (" + j.intValue() + " times)\n");
				}
			}
			return Boolean.TRUE;
		}
		else {
			return Boolean.FALSE;
		}
	}
}

@@ -715,17 +715,16 @@
 class);%0A
-%09
 %0A%09public
@@ -1584,24 +1584,47 @@
 %0A%09%09%09%09%7D%0A%09%09%09%7D%0A
+%09%09%09tmsg = tmsg.trim();%0A
 %09%09%09if (count
@@ -1927,16 +1927,30 @@
 ator();%0A
+%09%09%09int k = 1;%0A
 %09%09%09while
@@ -2089,32 +2089,43 @@
 TDERR.ret(stack,
+ k + %22. %22 +
  e.getKey() + %22%5C
@@ -2168,16 +2168,27 @@
 t(stack,
+ k + %22. %22 +
  e.getKe
@@ -2227,32 +2227,41 @@
 mes)%5Cn%22);%0A%09%09%09%09%7D%0A
+%09%09%09%09k++;%0A
 %09%09%09%7D%0A%09%09%09return B

nicer output