Fixes #70

Merged
Maece97 merged 1 commits from improvments-for-plugfest into dev 2021-11-16 18:10:58 +00:00
27 changed files with 307 additions and 95 deletions
Showing only changes of commit 44cc0929bd - Show all commits

View File

@ -29,12 +29,9 @@ public class ExecutionFinishedEventAdapter implements ExecutionFinishedEventPort
@Override @Override
public void publishExecutionFinishedEvent(ExecutionFinishedEvent event) { public void publishExecutionFinishedEvent(ExecutionFinishedEvent event) {
System.out.println("HI");
System.out.println(server);
String body = new JSONObject() String body = new JSONObject()
.put("taskID", event.getTaskID()) .put("taskID", event.getTaskID())
.put("result", event.getResult()) .put("outputData", event.getOutputData())
.put("status", event.getStatus()) .put("status", event.getStatus())
.toString(); .toString();
@ -46,8 +43,6 @@ public class ExecutionFinishedEventAdapter implements ExecutionFinishedEventPort
.build(); .build();
System.out.println(server);
try { try {
client.send(request, HttpResponse.BodyHandlers.ofString()); client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -57,7 +52,7 @@ public class ExecutionFinishedEventAdapter implements ExecutionFinishedEventPort
logger.log(Level.SEVERE, e.getLocalizedMessage(), e); logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
} }
logger.log(Level.INFO, "Finish execution event sent with result: {0}", event.getResult()); logger.log(Level.INFO, "Finish execution event sent with result: {0}", event.getOutputData());
} }

View File

@ -58,9 +58,8 @@ public class GetAssignmentAdapter implements GetAssignmentPort {
} }
JSONObject responseBody = new JSONObject(response.body()); JSONObject responseBody = new JSONObject(response.body());
String[] input = { "1", "+", "2" }; String inputData = responseBody.getString("inputData");
// TODO Add input in roster + tasklist return new Task(responseBody.getString("taskID"), inputData);
return new Task(responseBody.getString("taskID"), input);
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e); logger.log(Level.SEVERE, e.getLocalizedMessage(), e);

View File

@ -8,14 +8,14 @@ public class ExecutionFinishedEvent {
private String taskID; private String taskID;
@Getter @Getter
private String result; private String outputData;
@Getter @Getter
private String status; private String status;
public ExecutionFinishedEvent(String taskID, String result, String status) { public ExecutionFinishedEvent(String taskID, String outputData, String status) {
this.taskID = taskID; this.taskID = taskID;
this.result = result; this.outputData = outputData;
this.status = status; this.status = status;
} }
} }

View File

@ -71,13 +71,11 @@ public abstract class ExecutorBase {
logger.info("Starting execution"); logger.info("Starting execution");
this.status = ExecutorStatus.EXECUTING; this.status = ExecutorStatus.EXECUTING;
task.setResult(execution(task.getInput())); task.setOutputData(execution(task.getInputData()));
System.out.println(task.getResult());
// TODO implement logic if execution was not successful // TODO implement logic if execution was not successful
executionFinishedEventPort.publishExecutionFinishedEvent( executionFinishedEventPort.publishExecutionFinishedEvent(
new ExecutionFinishedEvent(task.getTaskID(), task.getResult(), "SUCCESS")); new ExecutionFinishedEvent(task.getTaskID(), task.getOutputData(), "SUCCESS"));
logger.info("Finish execution"); logger.info("Finish execution");
getAssignment(); getAssignment();
@ -87,6 +85,6 @@ public abstract class ExecutorBase {
* Implementation of the actual execution method of an executor * Implementation of the actual execution method of an executor
* @return the execution result * @return the execution result
**/ **/
protected abstract String execution(String... input); protected abstract String execution(String input);
} }

View File

@ -10,14 +10,16 @@ public class Task {
@Getter @Getter
@Setter @Setter
private String result; private String outputData;
// TODO maybe create a value object for inputData so we can make sure it is in the right
// format.
@Getter @Getter
private String[] input; private String inputData;
public Task(String taskID, String... input) { public Task(String taskID, String inputData) {
this.taskID = taskID; this.taskID = taskID;
this.input = input; this.inputData= inputData;
} }
} }

View File

@ -19,30 +19,45 @@ public class Executor extends ExecutorBase {
@Override @Override
protected protected
String execution(String... input) { String execution(String inputData) {
System.out.println(input); System.out.println(inputData);
double result = Double.NaN; String operator = "";
int a = Integer.parseInt(input[0]); if (inputData.contains("+")) {
int b = Integer.parseInt(input[2]); operator = "+";
String operation = input[1]; } else if (inputData.contains("-")) {
operator = "-";
// try { } else if (inputData.contains("*")) {
// TimeUnit.SECONDS.sleep(20); operator = "*";
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
if (operation == "+") {
result = a + b;
} else if (operation == "*") {
result = a * b;
} else if (operation == "-") {
result = a - b;
} }
System.out.println("finish"); // System.out.println(operator);
// double result = Double.NaN;
// System.out.print(inputData.split("+"));
// int a = Integer.parseInt(inputData.split(operator)[0]);
// int b = Integer.parseInt(inputData.split(operator)[1]);
// // try {
// // TimeUnit.SECONDS.sleep(20);
// // } catch (InterruptedException e) {
// // e.printStackTrace();
// // }
// if (operator.equalsIgnoreCase("+")) {
// result = a + b;
// } else if (operator.equalsIgnoreCase("*")) {
// result = a * b;
// } else if (operator.equalsIgnoreCase("-")) {
// result = a - b;
// }
// System.out.println("Result: " + result);
double result = 0.0;
return Double.toString(result); return Double.toString(result);
} }

View File

@ -28,7 +28,7 @@ public class Executor extends ExecutorBase {
@Override @Override
protected protected
String execution(String... input) { String execution(String input) {
String key = userToRobotPort.userToRobot(); String key = userToRobotPort.userToRobot();
try { try {

View File

@ -31,7 +31,8 @@ public class NewTaskController {
logger.info("New task with id:" + task.getTaskID()); logger.info("New task with id:" + task.getTaskID());
NewTaskCommand command = new NewTaskCommand(task.getTaskID(), task.getTaskType()); NewTaskCommand command = new NewTaskCommand(task.getTaskID(), task.getTaskType(),
task.getInputData());
boolean success = newTaskUseCase.addNewTaskToQueue(command); boolean success = newTaskUseCase.addNewTaskToQueue(command);

View File

@ -25,9 +25,9 @@ public class TaskCompletedController {
**/ **/
@PostMapping(path = "/task/completed", consumes = {"application/json"}) @PostMapping(path = "/task/completed", consumes = {"application/json"})
public ResponseEntity<Void> addNewTaskTaskToTaskList(@RequestBody Task task) { public ResponseEntity<Void> addNewTaskTaskToTaskList(@RequestBody Task task) {
System.out.println("TEST");
TaskCompletedCommand command = new TaskCompletedCommand(task.getTaskID(), TaskCompletedCommand command = new TaskCompletedCommand(task.getTaskID(),
task.getStatus(), task.getResult()); task.getStatus(), task.getOutputData());
taskCompletedUseCase.taskCompleted(command); taskCompletedUseCase.taskCompleted(command);

View File

@ -32,26 +32,26 @@ public class PublishTaskAssignedEventAdapter implements TaskAssignedEventPort {
@Override @Override
public void publishTaskAssignedEvent(TaskAssignedEvent event) { public void publishTaskAssignedEvent(TaskAssignedEvent event) {
String body = new JSONObject() // String body = new JSONObject()
.put("taskId", event.taskID) // .put("taskId", event.taskID)
.toString(); // .toString();
HttpClient client = HttpClient.newHttpClient(); // HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder() // HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(server + "/tasks/assignTask")) // .uri(URI.create(server + "/tasks/assignTask"))
.header("Content-Type", "application/json") // .header("Content-Type", "application/task+json")
.POST(HttpRequest.BodyPublishers.ofString(body)) // .POST(HttpRequest.BodyPublishers.ofString(body))
.build(); // .build();
try { // try {
client.send(request, HttpResponse.BodyHandlers.ofString()); // client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException e) { // } catch (InterruptedException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
Thread.currentThread().interrupt(); // Thread.currentThread().interrupt();
} catch (IOException e) { // } catch (IOException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e); // logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
} // }
} }
} }

View File

@ -32,17 +32,22 @@ public class PublishTaskCompletedEventAdapter implements TaskCompletedEventPort
@Override @Override
public void publishTaskCompleted(TaskCompletedEvent event) { public void publishTaskCompleted(TaskCompletedEvent event) {
System.out.println("PublishTaskCompletedEventAdapter.publishTaskCompleted()");
System.out.print(server);
String body = new JSONObject() String body = new JSONObject()
.put("taskId", event.taskID) .put("taskId", event.taskID)
.put("status", event.status) .put("status", event.status)
.put("taskResult", event.result) .put("outputData", event.result)
.toString(); .toString();
System.out.println(event.taskID);
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(server + "/tasks/completeTask")) .uri(URI.create(server + "/tasks/completeTask/" + event.taskID))
.header("Content-Type", "application/json") .header("Content-Type", "application/task+json")
.POST(HttpRequest.BodyPublishers.ofString(body)) .GET()
.build(); .build();

View File

@ -17,9 +17,13 @@ public class NewTaskCommand extends SelfValidating<NewTaskCommand> {
@NotNull @NotNull
private final ExecutorType taskType; private final ExecutorType taskType;
public NewTaskCommand(String taskID, ExecutorType taskType) { @NotNull
private final String inputData;
public NewTaskCommand(String taskID, ExecutorType taskType, String inputData) {
this.taskID = taskID; this.taskID = taskID;
this.taskType = taskType; this.taskType = taskType;
this.inputData = inputData;
this.validateSelf(); this.validateSelf();
} }
} }

View File

@ -34,7 +34,7 @@ public class NewTaskService implements NewTaskUseCase {
return false; return false;
} }
Task task = new Task(command.getTaskID(), command.getTaskType()); Task task = new Task(command.getTaskID(), command.getTaskType(), command.getInputData());
Roster.getInstance().addTaskToQueue(task); Roster.getInstance().addTaskToQueue(task);

View File

@ -14,7 +14,11 @@ public class Task {
@Getter @Getter
@Setter @Setter
private String result; private String inputData;
@Getter
@Setter
private String outputData;
@Getter @Getter
@Setter @Setter
@ -30,6 +34,12 @@ public class Task {
this.taskType = taskType; this.taskType = taskType;
} }
public Task(String taskID, ExecutorType taskType, String inputData) {
this.taskID = taskID;
this.taskType = taskType;
this.inputData = inputData;
}
public Task() {} public Task() {}
} }

View File

@ -55,16 +55,15 @@ public class AddNewTaskToTaskListWebController {
(payload.getOriginalTaskUri() == null) ? Optional.empty() (payload.getOriginalTaskUri() == null) ? Optional.empty()
: Optional.of(new Task.OriginalTaskUri(payload.getOriginalTaskUri())); : Optional.of(new Task.OriginalTaskUri(payload.getOriginalTaskUri()));
Optional<Task.InputData> inputData =
(payload.getInputData() == null) ? Optional.empty()
: Optional.of(new Task.InputData(payload.getInputData()));
AddNewTaskToTaskListCommand command = new AddNewTaskToTaskListCommand(taskName, taskType, AddNewTaskToTaskListCommand command = new AddNewTaskToTaskListCommand(taskName, taskType,
originalTaskUriOptional); originalTaskUriOptional, inputData);
Task createdTask = addNewTaskToTaskListUseCase.addNewTaskToTaskList(command); Task createdTask = addNewTaskToTaskListUseCase.addNewTaskToTaskList(command);
// When creating a task, the task's representation may include optional input data
if (payload.getInputData() != null) {
createdTask.setInputData(new Task.InputData(payload.getInputData()));
}
// Add the content type as a response header // Add the content type as a response header
HttpHeaders responseHeaders = new HttpHeaders(); HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add(HttpHeaders.CONTENT_TYPE, TaskJsonRepresentation.MEDIA_TYPE); responseHeaders.add(HttpHeaders.CONTENT_TYPE, TaskJsonRepresentation.MEDIA_TYPE);

View File

@ -8,8 +8,11 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ResponseStatusException;
@ -23,12 +26,17 @@ public class CompleteTaskWebController {
this.completeTaskUseCase = completeTaskUseCase; this.completeTaskUseCase = completeTaskUseCase;
} }
@PostMapping(path = "/tasks/completeTask", consumes = {TaskJsonRepresentation.MEDIA_TYPE}) @GetMapping(path = "/tasks/completeTask/{taskId}")
public ResponseEntity<String> completeTask (@RequestBody Task task){ public ResponseEntity<String> completeTask (@PathVariable("taskId") String taskId){
System.out.println("completeTask");
System.out.println(taskId);
String taskResult = "0";
try { try {
CompleteTaskCommand command = new CompleteTaskCommand( CompleteTaskCommand command = new CompleteTaskCommand(
task.getTaskId(), task.getTaskResult() new Task.TaskId(taskId), new Task.OutputData(taskResult)
); );
Task updateATask = completeTaskUseCase.completeTask(command); Task updateATask = completeTaskUseCase.completeTask(command);

View File

@ -0,0 +1,74 @@
package ch.unisg.tapastasks.tasks.adapter.out.web;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.github.fge.jsonpatch.JsonPatch;
import com.github.fge.jsonpatch.JsonPatchOperation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import ch.unisg.tapastasks.tasks.adapter.in.formats.TaskJsonPatchRepresentation;
import ch.unisg.tapastasks.tasks.application.port.out.ExternalTaskExecutedEvent;
import ch.unisg.tapastasks.tasks.application.port.out.ExternalTaskExecutedEventHandler;
@Component
@Primary
public class ExternalTaskExecutedWebAdapter implements ExternalTaskExecutedEventHandler {
Logger logger = Logger.getLogger(ExternalTaskExecutedWebAdapter.class.getName());
/**
* Updates an external task which got executed in our system.
**/
@Override
public void handleEvent(ExternalTaskExecutedEvent externalTaskExecutedEvent) {
JSONObject op1;
JSONObject op2;
try {
op1 = new JSONObject()
.put("op", "replace")
.put("path", "/taskStatus")
.put("value", "EXECUTED");
op2 = new JSONObject()
.put("op", "add")
.put("path", "/outputData")
.put("value", "0");
} catch (JSONException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
return;
}
String body = new JSONArray().put(op1).put(op2).toString();
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(externalTaskExecutedEvent.getOriginalTaskUri().getValue()))
.header("Content-Type", "application/json")
.method("PATCH", HttpRequest.BodyPublishers.ofString(body))
.build();
try {
client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
Thread.currentThread().interrupt();
} catch (IOException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
}

View File

@ -29,6 +29,7 @@ public class PublishNewTaskAddedEventWebAdapter implements NewTaskAddedEventPort
var values = new HashMap<String, String>() {{ var values = new HashMap<String, String>() {{
put("taskID", event.taskId); put("taskID", event.taskId);
put("taskType", event.taskType); put("taskType", event.taskType);
put("inputData", event.inputData);
}}; }};
var objectMapper = new ObjectMapper(); var objectMapper = new ObjectMapper();

View File

@ -19,11 +19,19 @@ public class AddNewTaskToTaskListCommand extends SelfValidating<AddNewTaskToTask
@Getter @Getter
private final Optional<Task.OriginalTaskUri> originalTaskUri; private final Optional<Task.OriginalTaskUri> originalTaskUri;
public AddNewTaskToTaskListCommand(Task.TaskName taskName, Task.TaskType taskType, @Getter
Optional<Task.OriginalTaskUri> originalTaskUri) { private final Optional<Task.InputData> inputData;
public AddNewTaskToTaskListCommand(
Task.TaskName taskName,
Task.TaskType taskType,
Optional<Task.OriginalTaskUri> originalTaskUri,
Optional<Task.InputData> inputData
) {
this.taskName = taskName; this.taskName = taskName;
this.taskType = taskType; this.taskType = taskType;
this.originalTaskUri = originalTaskUri; this.originalTaskUri = originalTaskUri;
this.inputData = inputData;
this.validateSelf(); this.validateSelf();
} }

View File

@ -1,6 +1,7 @@
package ch.unisg.tapastasks.tasks.application.port.in; package ch.unisg.tapastasks.tasks.application.port.in;
import ch.unisg.tapastasks.common.SelfValidating; import ch.unisg.tapastasks.common.SelfValidating;
import ch.unisg.tapastasks.tasks.domain.Task.OutputData;
import ch.unisg.tapastasks.tasks.domain.Task.TaskId; import ch.unisg.tapastasks.tasks.domain.Task.TaskId;
import ch.unisg.tapastasks.tasks.domain.Task.TaskResult; import ch.unisg.tapastasks.tasks.domain.Task.TaskResult;
import lombok.Value; import lombok.Value;
@ -13,11 +14,11 @@ public class CompleteTaskCommand extends SelfValidating<CompleteTaskCommand> {
private final TaskId taskId; private final TaskId taskId;
@NotNull @NotNull
private final TaskResult taskResult; private final OutputData outputData;
public CompleteTaskCommand(TaskId taskId, TaskResult taskResult){ public CompleteTaskCommand(TaskId taskId, OutputData outputData){
this.taskId = taskId; this.taskId = taskId;
this.taskResult = taskResult; this.outputData = outputData;
this.validateSelf(); this.validateSelf();
} }
} }

View File

@ -0,0 +1,28 @@
package ch.unisg.tapastasks.tasks.application.port.out;
import javax.validation.constraints.NotNull;
import ch.unisg.tapastasks.common.SelfValidating;
import ch.unisg.tapastasks.tasks.domain.Task;
import lombok.Getter;
import lombok.Value;
@Value
public class ExternalTaskExecutedEvent extends SelfValidating<ExternalTaskExecutedEvent> {
@NotNull
private final Task.TaskId taskId;
@Getter
private final Task.OriginalTaskUri originalTaskUri;
@Getter
private final Task.OutputData outputData;
public ExternalTaskExecutedEvent(Task.TaskId taskId, Task.OriginalTaskUri originalTaskUri, Task.OutputData outputData) {
this.taskId = taskId;
this.originalTaskUri = originalTaskUri;
this.outputData = outputData;
this.validateSelf();
}
}

View File

@ -0,0 +1,5 @@
package ch.unisg.tapastasks.tasks.application.port.out;
public interface ExternalTaskExecutedEventHandler {
void handleEvent(ExternalTaskExecutedEvent externalTaskExecutedEvent);
}

View File

@ -22,12 +22,26 @@ public class AddNewTaskToTaskListService implements AddNewTaskToTaskListUseCase
public Task addNewTaskToTaskList(AddNewTaskToTaskListCommand command) { public Task addNewTaskToTaskList(AddNewTaskToTaskListCommand command) {
TaskList taskList = TaskList.getTapasTaskList(); TaskList taskList = TaskList.getTapasTaskList();
Task newTask = (command.getOriginalTaskUri().isPresent()) ? Task newTask;
// Create a delegated task that points back to the original task
taskList.addNewTaskWithNameAndTypeAndOriginalTaskUri(command.getTaskName(), System.out.println("TEST:");
command.getTaskType(), command.getOriginalTaskUri().get()) System.out.println(command.getInputData().get());
// Create an original task
: taskList.addNewTaskWithNameAndType(command.getTaskName(), command.getTaskType()); if (command.getOriginalTaskUri().isPresent() && command.getInputData().isPresent()) {
System.out.println("TEST2:");
newTask = taskList.addNewTaskWithNameAndTypeAndOriginalTaskUriAndInputData(command.getTaskName(),
command.getTaskType(), command.getOriginalTaskUri().get(), command.getInputData().get());
} else if (command.getOriginalTaskUri().isPresent()) {
newTask = taskList.addNewTaskWithNameAndTypeAndOriginalTaskUri(command.getTaskName(),
command.getTaskType(), command.getOriginalTaskUri().get());
} else if (command.getOriginalTaskUri().isPresent()) {
newTask = null;
} else {
newTask = taskList.addNewTaskWithNameAndType(command.getTaskName(), command.getTaskType());
}
System.out.println("TEST");
System.out.println(newTask.getInputData());
//Here we are using the application service to emit the domain event to the outside of the bounded context. //Here we are using the application service to emit the domain event to the outside of the bounded context.
//This event should be considered as a light-weight "integration event" to communicate with other services. //This event should be considered as a light-weight "integration event" to communicate with other services.
@ -35,8 +49,13 @@ public class AddNewTaskToTaskListService implements AddNewTaskToTaskListUseCase
//not recommended to emit a domain event via an application service! You should first emit the domain event in //not recommended to emit a domain event via an application service! You should first emit the domain event in
//the core and then the integration event in the application layer. //the core and then the integration event in the application layer.
if (newTask != null) { if (newTask != null) {
NewTaskAddedEvent newTaskAdded = new NewTaskAddedEvent(newTask.getTaskName().getValue(), NewTaskAddedEvent newTaskAdded = new NewTaskAddedEvent(
taskList.getTaskListName().getValue(), newTask.getTaskId().getValue(), newTask.getTaskType().getValue()); newTask.getTaskName().getValue(),
taskList.getTaskListName().getValue(),
newTask.getTaskId().getValue(),
newTask.getTaskType().getValue(),
newTask.getInputData().getValue()
);
newTaskAddedEventPort.publishNewTaskAddedEvent(newTaskAdded); newTaskAddedEventPort.publishNewTaskAddedEvent(newTaskAdded);
} }

View File

@ -2,10 +2,11 @@ package ch.unisg.tapastasks.tasks.application.service;
import ch.unisg.tapastasks.tasks.application.port.in.CompleteTaskCommand; import ch.unisg.tapastasks.tasks.application.port.in.CompleteTaskCommand;
import ch.unisg.tapastasks.tasks.application.port.in.CompleteTaskUseCase; import ch.unisg.tapastasks.tasks.application.port.in.CompleteTaskUseCase;
import ch.unisg.tapastasks.tasks.application.port.out.ExternalTaskExecutedEvent;
import ch.unisg.tapastasks.tasks.application.port.out.ExternalTaskExecutedEventHandler;
import ch.unisg.tapastasks.tasks.domain.Task; import ch.unisg.tapastasks.tasks.domain.Task;
import ch.unisg.tapastasks.tasks.domain.Task.*; import ch.unisg.tapastasks.tasks.domain.Task.*;
import ch.unisg.tapastasks.tasks.domain.TaskList; import ch.unisg.tapastasks.tasks.domain.TaskList;
import lombok.Getter;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -17,15 +18,26 @@ import java.util.Optional;
@Transactional @Transactional
public class CompleteTaskService implements CompleteTaskUseCase { public class CompleteTaskService implements CompleteTaskUseCase {
private final ExternalTaskExecutedEventHandler externalTaskExecutedEventHandler;
@Override @Override
public Task completeTask(CompleteTaskCommand command){ public Task completeTask(CompleteTaskCommand command){
TaskList taskList = TaskList.getTapasTaskList(); TaskList taskList = TaskList.getTapasTaskList();
Optional<Task> updatedTask = taskList.retrieveTaskById(command.getTaskId()); Optional<Task> updatedTask = taskList.retrieveTaskById(command.getTaskId());
Task newTask = updatedTask.get(); Task newTask = updatedTask.get();
newTask.taskResult = new TaskResult(command.getTaskResult().getValue()); newTask.taskResult = new TaskResult(command.getOutputData().getValue());
newTask.taskStatus = new TaskStatus(Task.Status.EXECUTED); newTask.taskStatus = new TaskStatus(Task.Status.EXECUTED);
if (!newTask.getOriginalTaskUri().getValue().equalsIgnoreCase("")) {
ExternalTaskExecutedEvent event = new ExternalTaskExecutedEvent(
newTask.getTaskId(),
newTask.getOriginalTaskUri(),
newTask.getOutputData()
);
externalTaskExecutedEventHandler.handleEvent(event);
}
return newTask; return newTask;
} }
} }

View File

@ -6,12 +6,14 @@ public class NewTaskAddedEvent {
public String taskListName; public String taskListName;
public String taskId; public String taskId;
public String taskType; public String taskType;
public String inputData;
public NewTaskAddedEvent(String taskName, String taskListName, String taskId, String taskType) { public NewTaskAddedEvent(String taskName, String taskListName, String taskId, String taskType, String inputData) {
this.taskName = taskName; this.taskName = taskName;
this.taskListName = taskListName; this.taskListName = taskListName;
this.taskId = taskId; this.taskId = taskId;
this.taskType = taskType; this.taskType = taskType;
this.inputData = inputData;
} }
} }

View File

@ -51,6 +51,18 @@ public class Task {
this.outputData = null; this.outputData = null;
} }
public Task(TaskName taskName, TaskType taskType, OriginalTaskUri taskUri, InputData inputData) {
this.taskName = taskName;
this.taskType = taskType;
this.taskStatus = new TaskStatus(Status.OPEN);
this.taskId = new TaskId(UUID.randomUUID().toString());
this.taskResult = new TaskResult("");
this.originalTaskUri = taskUri;
this.inputData = inputData;
this.outputData = null;
}
protected static Task createTaskWithNameAndType(TaskName name, TaskType type) { protected static Task createTaskWithNameAndType(TaskName name, TaskType type) {
//This is a simple debug message to see that the request has reached the right method in the core //This is a simple debug message to see that the request has reached the right method in the core
System.out.println("New Task: " + name.getValue() + " " + type.getValue()); System.out.println("New Task: " + name.getValue() + " " + type.getValue());
@ -62,6 +74,11 @@ public class Task {
return new Task(name, type, originalTaskUri); return new Task(name, type, originalTaskUri);
} }
protected static Task createTaskWithNameAndTypeAndOriginalTaskUriAndInputData(TaskName name, TaskType type,
OriginalTaskUri originalTaskUri, InputData inputData) {
return new Task(name, type, originalTaskUri, inputData);
}
@Value @Value
public static class TaskId { public static class TaskId {
String value; String value;

View File

@ -48,6 +48,15 @@ public class TaskList {
return newTask; return newTask;
} }
public Task addNewTaskWithNameAndTypeAndOriginalTaskUriAndInputData(Task.TaskName name, Task.TaskType type,
Task.OriginalTaskUri originalTaskUri, Task.InputData inputData) {
Task newTask = Task.createTaskWithNameAndTypeAndOriginalTaskUriAndInputData(name, type, originalTaskUri, inputData);
this.addNewTaskToList(newTask);
return newTask;
}
private void addNewTaskToList(Task newTask) { private void addNewTaskToList(Task newTask) {
//Here we would also publish a domain event to other entities in the core interested in this event. //Here we would also publish a domain event to other entities in the core interested in this event.
//However, we skip this here as it makes the core even more complex (e.g., we have to implement a light-weight //However, we skip this here as it makes the core even more complex (e.g., we have to implement a light-weight