This commit is contained in:
Marcel 2021-11-16 19:09:38 +01:00
parent bce3619638
commit 44cc0929bd
27 changed files with 307 additions and 95 deletions

View File

@ -29,12 +29,9 @@ public class ExecutionFinishedEventAdapter implements ExecutionFinishedEventPort
@Override
public void publishExecutionFinishedEvent(ExecutionFinishedEvent event) {
System.out.println("HI");
System.out.println(server);
String body = new JSONObject()
.put("taskID", event.getTaskID())
.put("result", event.getResult())
.put("outputData", event.getOutputData())
.put("status", event.getStatus())
.toString();
@ -46,8 +43,6 @@ public class ExecutionFinishedEventAdapter implements ExecutionFinishedEventPort
.build();
System.out.println(server);
try {
client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException e) {
@ -57,7 +52,7 @@ public class ExecutionFinishedEventAdapter implements ExecutionFinishedEventPort
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());
String[] input = { "1", "+", "2" };
// TODO Add input in roster + tasklist
return new Task(responseBody.getString("taskID"), input);
String inputData = responseBody.getString("inputData");
return new Task(responseBody.getString("taskID"), inputData);
} catch (InterruptedException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);

View File

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

View File

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

View File

@ -19,30 +19,45 @@ public class Executor extends ExecutorBase {
@Override
protected
String execution(String... input) {
String execution(String inputData) {
System.out.println(input);
System.out.println(inputData);
double result = Double.NaN;
int a = Integer.parseInt(input[0]);
int b = Integer.parseInt(input[2]);
String operation = input[1];
// try {
// TimeUnit.SECONDS.sleep(20);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
if (operation == "+") {
result = a + b;
} else if (operation == "*") {
result = a * b;
} else if (operation == "-") {
result = a - b;
String operator = "";
if (inputData.contains("+")) {
operator = "+";
} else if (inputData.contains("-")) {
operator = "-";
} else if (inputData.contains("*")) {
operator = "*";
}
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);
}

View File

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

View File

@ -31,7 +31,8 @@ public class NewTaskController {
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);

View File

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

View File

@ -32,26 +32,26 @@ public class PublishTaskAssignedEventAdapter implements TaskAssignedEventPort {
@Override
public void publishTaskAssignedEvent(TaskAssignedEvent event) {
String body = new JSONObject()
.put("taskId", event.taskID)
.toString();
// String body = new JSONObject()
// .put("taskId", event.taskID)
// .toString();
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(server + "/tasks/assignTask"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
// HttpClient client = HttpClient.newHttpClient();
// HttpRequest request = HttpRequest.newBuilder()
// .uri(URI.create(server + "/tasks/assignTask"))
// .header("Content-Type", "application/task+json")
// .POST(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);
}
// 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

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

View File

@ -17,9 +17,13 @@ public class NewTaskCommand extends SelfValidating<NewTaskCommand> {
@NotNull
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.taskType = taskType;
this.inputData = inputData;
this.validateSelf();
}
}

View File

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

View File

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

View File

@ -55,16 +55,15 @@ public class AddNewTaskToTaskListWebController {
(payload.getOriginalTaskUri() == null) ? Optional.empty()
: 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,
originalTaskUriOptional);
originalTaskUriOptional, inputData);
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
HttpHeaders responseHeaders = new HttpHeaders();
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.HttpStatus;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
@ -23,12 +26,17 @@ public class CompleteTaskWebController {
this.completeTaskUseCase = completeTaskUseCase;
}
@PostMapping(path = "/tasks/completeTask", consumes = {TaskJsonRepresentation.MEDIA_TYPE})
public ResponseEntity<String> completeTask (@RequestBody Task task){
@GetMapping(path = "/tasks/completeTask/{taskId}")
public ResponseEntity<String> completeTask (@PathVariable("taskId") String taskId){
System.out.println("completeTask");
System.out.println(taskId);
String taskResult = "0";
try {
CompleteTaskCommand command = new CompleteTaskCommand(
task.getTaskId(), task.getTaskResult()
new Task.TaskId(taskId), new Task.OutputData(taskResult)
);
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>() {{
put("taskID", event.taskId);
put("taskType", event.taskType);
put("inputData", event.inputData);
}};
var objectMapper = new ObjectMapper();

View File

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

View File

@ -1,6 +1,7 @@
package ch.unisg.tapastasks.tasks.application.port.in;
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.TaskResult;
import lombok.Value;
@ -13,11 +14,11 @@ public class CompleteTaskCommand extends SelfValidating<CompleteTaskCommand> {
private final TaskId taskId;
@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.taskResult = taskResult;
this.outputData = outputData;
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) {
TaskList taskList = TaskList.getTapasTaskList();
Task newTask = (command.getOriginalTaskUri().isPresent()) ?
// Create a delegated task that points back to the original task
taskList.addNewTaskWithNameAndTypeAndOriginalTaskUri(command.getTaskName(),
command.getTaskType(), command.getOriginalTaskUri().get())
// Create an original task
: taskList.addNewTaskWithNameAndType(command.getTaskName(), command.getTaskType());
Task newTask;
System.out.println("TEST:");
System.out.println(command.getInputData().get());
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.
//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
//the core and then the integration event in the application layer.
if (newTask != null) {
NewTaskAddedEvent newTaskAdded = new NewTaskAddedEvent(newTask.getTaskName().getValue(),
taskList.getTaskListName().getValue(), newTask.getTaskId().getValue(), newTask.getTaskType().getValue());
NewTaskAddedEvent newTaskAdded = new NewTaskAddedEvent(
newTask.getTaskName().getValue(),
taskList.getTaskListName().getValue(),
newTask.getTaskId().getValue(),
newTask.getTaskType().getValue(),
newTask.getInputData().getValue()
);
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.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.TaskList;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@ -17,15 +18,26 @@ import java.util.Optional;
@Transactional
public class CompleteTaskService implements CompleteTaskUseCase {
private final ExternalTaskExecutedEventHandler externalTaskExecutedEventHandler;
@Override
public Task completeTask(CompleteTaskCommand command){
TaskList taskList = TaskList.getTapasTaskList();
Optional<Task> updatedTask = taskList.retrieveTaskById(command.getTaskId());
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);
if (!newTask.getOriginalTaskUri().getValue().equalsIgnoreCase("")) {
ExternalTaskExecutedEvent event = new ExternalTaskExecutedEvent(
newTask.getTaskId(),
newTask.getOriginalTaskUri(),
newTask.getOutputData()
);
externalTaskExecutedEventHandler.handleEvent(event);
}
return newTask;
}
}

View File

@ -6,12 +6,14 @@ public class NewTaskAddedEvent {
public String taskListName;
public String taskId;
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.taskListName = taskListName;
this.taskId = taskId;
this.taskType = taskType;
this.inputData = inputData;
}
}

View File

@ -51,6 +51,18 @@ public class Task {
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) {
//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());
@ -62,6 +74,11 @@ public class Task {
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
public static class TaskId {
String value;

View File

@ -48,6 +48,15 @@ public class TaskList {
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) {
//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