package io.trygvis.queue; import java.util.Date; import java.util.List; import static io.trygvis.queue.Task.TaskState.*; import static java.util.Arrays.asList; public class Task { public enum TaskState { NEW, PROCESSING, OK, FAILED } private final long id; public final Long parent; public final String queue; public final TaskState state; public final Date scheduled; public final Date lastRun; public final int runCount; public final Date completed; public final List arguments; public Task(long id, Long parent, String queue, TaskState state, Date scheduled, Date lastRun, int runCount, Date completed, List arguments) { this.id = id; this.parent = parent; this.queue = queue; this.state = state; this.scheduled = scheduled; this.lastRun = lastRun; this.runCount = runCount; this.completed = completed; this.arguments = arguments; } public Task markProcessing() { return new Task(id, parent, queue, PROCESSING, scheduled, new Date(), runCount + 1, completed, arguments); } public Task markOk(Date completed) { return new Task(id, parent, queue, OK, scheduled, lastRun, runCount, completed, arguments); } public Task markFailed(Date now) { return new Task(id, parent, queue, FAILED, scheduled, lastRun, runCount, completed, arguments); } public String toString() { return "Task{" + "id=" + id + ", parent=" + parent + ", queue=" + queue + ", state=" + state + ", scheduled=" + scheduled + ", lastRun=" + lastRun + ", runCount=" + runCount + ", completed=" + completed + ", arguments='" + arguments + '\'' + '}'; } public long id() { if (id == 0) { throw new RuntimeException("This task has not been persisted yet."); } return id; } public boolean isDone() { return completed != null; } public Task childTask(String name, Date scheduled, String... arguments) { return new Task(0, id(), name, NEW, scheduled, null, 0, null, asList(arguments)); } public static Task newTask(String name, Date scheduled, String... arguments) { return new Task(0, null, name, NEW, scheduled, null, 0, null, asList(arguments)); } public static Task newTask(String name, Date scheduled, List arguments) { return new Task(0, null, name, NEW, scheduled, null, 0, null, arguments); } public static List stringToArguments(String arguments) { return asList(arguments.split(",")); } public static String argumentsToString(List arguments) { StringBuilder builder = new StringBuilder(); for (int i = 0, argumentsLength = arguments.size(); i < argumentsLength; i++) { String argument = arguments.get(i); if (argument.contains(",")) { throw new RuntimeException("The argument string can't contain a comma."); } if (i > 0) { builder.append(','); } builder.append(argument); } return builder.toString(); } }