ATaskProvider.java

package de.dlr.bt.stc.task;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.apache.commons.configuration2.ex.ConfigurationException;
import org.greenrobot.eventbus.EventBus;

import de.dlr.bt.stc.entities.TaskLifecycle;
import de.dlr.bt.stc.eventbus.TaskModifiedEvent;
import de.dlr.bt.stc.eventbus.TaskModifiedEvent.TaskModificationType;
import de.dlr.bt.stc.exceptions.STCException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class ATaskProvider<T extends ITask> {
	protected final Map<String, TaskLifecycle<T>> taskLifecycles = new HashMap<>();
	protected final EventBus managementEventBus;

	protected ATaskProvider(EventBus managementEventBus) {
		this.managementEventBus = managementEventBus;
	}

	public boolean initializeTasks() {
		var ok = true;
		for (var task : taskLifecycles.values())
			ok &= initializeTask(task);

		return ok;
	}

	public boolean startTasks() {
		var ok = true;
		for (var task : taskLifecycles.values())
			ok &= startTask(task);

		return ok;
	}

	public void stopTasks() {
		for (var task : taskLifecycles.values())
			stopTask(task);
	}

	public void cleanupTasks() {
		for (var task : taskLifecycles.values())
			cleanupTask(task);
	}

	public Map<String, ITask> getTasks() {
		return taskLifecycles.entrySet().stream()
				.collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().getTask()));
	}

	protected boolean initializeTask(TaskLifecycle<T> task) {
		if (task.isInitialized()) {
			// already initialized
			return true;
		}

		var ok = true;
		try {
			task.getTask().initializeTask();
			managementEventBus.post(new TaskModifiedEvent(task.getTask(), TaskModificationType.INITIALIZE));
		} catch (ConfigurationException e) {
			ok = false;
		}
		task.setInitialized(ok);
		return ok;
	}

	protected boolean startTask(TaskLifecycle<T> task) {
		if (!task.isInitialized()) {
			// Return false when task is not yet initialized
			return false;
		} else if (task.isStarted()) {
			// Return true when task is already started
			return true;
		}

		boolean ok = true;
		try {
			task.getTask().startTask();
			managementEventBus.post(new TaskModifiedEvent(task.getTask(), TaskModificationType.START));
		} catch (STCException ex) {
			ok = false;
		}
		task.setStarted(ok);
		return ok;
	}

	protected void stopTask(TaskLifecycle<T> task) {
		task.getTask().stopTask();
		try {
			task.getTask().joinTask();
		} catch (InterruptedException ie) {
			log.error("ATaskProvider thread was interrupted!");
			Thread.currentThread().interrupt();
		}
		managementEventBus.post(new TaskModifiedEvent(task.getTask(), TaskModificationType.STOP));
		task.setStarted(false);
	}

	protected void cleanupTask(TaskLifecycle<T> task) {
		managementEventBus.post(new TaskModifiedEvent(task.getTask(), TaskModificationType.REMOVE));
		task.setInitialized(false);
	}

}