/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2009 Bull S.A.S
 * Contact: jonas-team@objectweb.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or 1any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.cluster.test.common;

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

public class Worker implements Runnable {
    /**
     * Tasks.
     */
    List<RunnableTask> tasks  = new ArrayList<RunnableTask>();
    /**
     * Tasks failures
     */
    Map<String, Exception> tasksFailures = new HashMap<String, Exception>();
    public void run() {
        // TODO Auto-generated method stub
        for (Iterator<RunnableTask> iterator = tasks.iterator(); iterator.hasNext();) {
            RunnableTask task = iterator.next();
            Thread thr = new Thread(null, task, task.getName());
            thr.start();
        }
    }
    /**
     * Add a task.
     * @param task
     */
    public void addTask(final RunnableTask task) {
        tasks.add(task);
    }
    /**
     * Get the tasks.
     * @return
     */
    public List<RunnableTask> getTasks() {
        return tasks;
    }
    /**
     * Retunr tru if any task failed.
     * @return
     */
    public boolean hasFailure() {
         Exception e = null;
         for (Iterator<RunnableTask> iterator = tasks.iterator(); iterator.hasNext();) {
             RunnableTask task = iterator.next();
             e = task.getException();
             if(e != null) {
                 tasksFailures.put(task.getName(), e);
             }
         }
        return !tasksFailures.isEmpty();
    }
    /**
     * Clear the worker
     */
    public void clear() {
        tasks.clear();
        tasksFailures.clear();
    }

    /**
     * Gets failure per tasks
     */
    public Map<?, ?> getTasksFailures() {
        return tasksFailures;
    }

}
