Merging dev to main #107

Merged
Maece97 merged 52 commits from dev into main 2021-12-23 16:12:19 +00:00
34 changed files with 435 additions and 395 deletions
Showing only changes of commit 5803380263 - Show all commits

View File

@ -67,8 +67,9 @@ services:
- ./:/data/ - ./:/data/
environment: environment:
mqtt.broker.uri: tcp://broker.hivemq.com:1883 mqtt.broker.uri: tcp://broker.hivemq.com:1883
discovery.endpoint.uri: https://tapas-auction-house.86.119.35.213.nip.io/discovery/ discovery.endpoint.uri: https://tapas-auction-house.86-119-34-242.nip.io
auction.house.uri: https://tapas-auction-house.86-119-35-40.nip.io auction.house.uri: https://tapas-auction-house.86-119-35-40.nip.io
tasks.list.uri: https://tapas-tasks.86-119-35-40.nip.io
labels: labels:
- "traefik.enable=true" - "traefik.enable=true"
- "traefik.http.routers.tapas-auction-house.rule=Host(`tapas-auction-house.${PUB_IP}.nip.io`)" - "traefik.http.routers.tapas-auction-house.rule=Host(`tapas-auction-house.${PUB_IP}.nip.io`)"
@ -91,6 +92,7 @@ services:
auction.house.uri: http://tapas-auction-house:8086 auction.house.uri: http://tapas-auction-house:8086
executor.robot.uri: http://executor-robot:8084 executor.robot.uri: http://executor-robot:8084
executor.computation.uri: http://executor-computation:8085 executor.computation.uri: http://executor-computation:8085
executor.humidity.uri: http://executor-humidity:8087
mqtt.broker.uri: tcp://broker.hivemq.com:1883 mqtt.broker.uri: tcp://broker.hivemq.com:1883
spring.data.mongodb.uri: mongodb://root:password@tapas-db:27017 spring.data.mongodb.uri: mongodb://root:password@tapas-db:27017
labels: labels:
@ -164,3 +166,24 @@ services:
- "traefik.http.routers.executor-robot.tls=true" - "traefik.http.routers.executor-robot.tls=true"
- "traefik.http.routers.executor-robot.entryPoints=web,websecure" - "traefik.http.routers.executor-robot.entryPoints=web,websecure"
- "traefik.http.routers.executor-robot.tls.certresolver=le" - "traefik.http.routers.executor-robot.tls.certresolver=le"
executor-humidity:
image: openjdk
command: "java -jar /data/executor-humidity-0.0.1-SNAPSHOT.jar"
restart: unless-stopped
depends_on:
- executor-pool
- roster
- tapas-db
volumes:
- ./:/data/
environment:
EXECUTOR_POOL_URI: http://executor-pool:8083
ROSTER_URI: http://roster:8082
labels:
- "traefik.enable=true"
- "traefik.http.routers.executor-computation.rule=Host(`executor-humidity.${PUB_IP}.nip.io`)"
- "traefik.http.routers.executor-computation.service=executor-computation"
- "traefik.http.services.executor-computation.loadbalancer.server.port=8087"
- "traefik.http.routers.executor-computation.tls=true"
- "traefik.http.routers.executor-computation.entryPoints=web,websecure"
- "traefik.http.routers.executor-computation.tls.certresolver=le"

View File

@ -55,6 +55,10 @@ jobs:
run: mvn -f executor-robot/pom.xml --batch-mode --update-snapshots verify run: mvn -f executor-robot/pom.xml --batch-mode --update-snapshots verify
- run: cp ./executor-robot/target/executor-robot-0.0.1-SNAPSHOT.jar ./target - run: cp ./executor-robot/target/executor-robot-0.0.1-SNAPSHOT.jar ./target
- name: Build executor-humidity service
run: mvn -f executor-humidity/pom.xml --batch-mode --update-snapshots verify
- run: cp ./executor-humidity/target/executor-humidity-0.0.1-SNAPSHOT.jar ./target
- name: Build tapas-task service - name: Build tapas-task service
run: mvn -f tapas-tasks/pom.xml --batch-mode --update-snapshots verify run: mvn -f tapas-tasks/pom.xml --batch-mode --update-snapshots verify
- run: cp ./tapas-tasks/target/tapas-tasks-0.0.1-SNAPSHOT.jar ./target - run: cp ./tapas-tasks/target/tapas-tasks-0.0.1-SNAPSHOT.jar ./target
@ -103,5 +107,6 @@ jobs:
cd /home/${{ secrets.SSH_USER }}/ cd /home/${{ secrets.SSH_USER }}/
touch acme.json touch acme.json
sudo chmod 0600 acme.json sudo chmod 0600 acme.json
sudo docker-compose down --remove-orphans
sudo echo "PUB_IP=$(wget -qO- http://ipecho.net/plain | xargs echo)" | sed -e 's/\./-/g' > .env sudo echo "PUB_IP=$(wget -qO- http://ipecho.net/plain | xargs echo)" | sed -e 's/\./-/g' > .env
sudo docker-compose up -d --build --force-recreate sudo docker-compose up -d

View File

@ -33,12 +33,11 @@ public abstract class ExecutorBase {
Logger logger = Logger.getLogger(ExecutorBase.class.getName()); Logger logger = Logger.getLogger(ExecutorBase.class.getName());
protected ExecutorBase(ExecutorType executorType) { protected ExecutorBase(ExecutorType executorType, String uri) {
logger.info("ExecutorBase | Starting Executor"); logger.info("ExecutorBase | Starting Executor");
this.status = ExecutorStatus.STARTING_UP; this.status = ExecutorStatus.STARTING_UP;
this.executorType = executorType; this.executorType = executorType;
// TODO set this automaticly this.executorURI = new ExecutorURI(uri);
this.executorURI = new ExecutorURI("http://localhost:8084");
// TODO do this in main // TODO do this in main
// Notify executor-pool about existence. If executor-pools response is successfull start with getting an assignment, else shut down executor. // Notify executor-pool about existence. If executor-pools response is successfull start with getting an assignment, else shut down executor.
logger.info("ExecutorBase | Notifying executor-pool about existens"); logger.info("ExecutorBase | Notifying executor-pool about existens");

View File

@ -1,7 +1,7 @@
package ch.unisg.executorbase.executor.domain; package ch.unisg.executorbase.executor.domain;
public enum ExecutorType { public enum ExecutorType {
COMPUTATION, ROBOT, HUMIDITY; COMPUTATION, SMALLROBOT, HUMIDITY;
/** /**
* Checks if the give executor type exists. * Checks if the give executor type exists.

View File

@ -67,6 +67,17 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId> <artifactId>spring-boot-test</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js</artifactId>
<version>21.3.0</version>
</dependency>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js-scriptengine</artifactId>
<version>21.3.0</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -15,14 +15,6 @@ public class ExecutorcomputationApplication {
static Logger logger = Logger.getLogger(ExecutorcomputationApplication.class.getName()); static Logger logger = Logger.getLogger(ExecutorcomputationApplication.class.getName());
public static void main(String[] args) { public static void main(String[] args) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
Thread.currentThread().interrupt();
}
SpringApplication.run(ExecutorcomputationApplication.class, args); SpringApplication.run(ExecutorcomputationApplication.class, args);
Executor.getExecutor(); Executor.getExecutor();
} }

View File

@ -1,7 +1,6 @@
package ch.unisg.executorcomputation.executor.domain; package ch.unisg.executorcomputation.executor.domain;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.script.ScriptEngine; import javax.script.ScriptEngine;
@ -15,21 +14,20 @@ public class Executor extends ExecutorBase {
private static Logger executorLogger = Logger.getLogger(Executor.class.getName()); private static Logger executorLogger = Logger.getLogger(Executor.class.getName());
private static final Executor executor = new Executor(ExecutorType.COMPUTATION); private static final Executor executor = new Executor(ExecutorType.COMPUTATION, "http://localhost:8085");
public static Executor getExecutor() { public static Executor getExecutor() {
return executor; return executor;
} }
private Executor(ExecutorType executorType) { private Executor(ExecutorType executorType, String uri) {
super(executorType); super(executorType, uri);
} }
@Override @Override
protected protected
String execution(String inputData) { String execution(String inputData) {
executorLogger.info("TEST");
executorLogger.info("Executor | Starting execution with inputData: " + inputData); executorLogger.info("Executor | Starting execution with inputData: " + inputData);
ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngineManager mgr = new ScriptEngineManager();
@ -45,10 +43,11 @@ public class Executor extends ExecutorBase {
} }
try { try {
TimeUnit.SECONDS.sleep(5); TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) { } catch (InterruptedException e) {
executorLogger.log(Level.SEVERE, e.getLocalizedMessage(), e); return result;
Thread.currentThread().interrupt(); // executorLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
// Thread.currentThread().interrupt();
} }
executorLogger.info("Executor | Finish execution"); executorLogger.info("Executor | Finish execution");

View File

@ -11,7 +11,7 @@
</parent> </parent>
<groupId>ch.unisg</groupId> <groupId>ch.unisg</groupId>
<artifactId>executor-humidity</artifactId> <artifactId>executor-humidity</artifactId>
<version>1.0-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>executor-humidity</name> <name>executor-humidity</name>
<description>Demo project for Spring Boot</description> <description>Demo project for Spring Boot</description>
<properties> <properties>

View File

@ -4,17 +4,16 @@ import ch.unisg.executorbase.executor.domain.ExecutorBase;
import ch.unisg.executorbase.executor.domain.ExecutorType; import ch.unisg.executorbase.executor.domain.ExecutorType;
import ch.unisg.executorhumidity.executor.adapter.out.GetHumidityAdapter; import ch.unisg.executorhumidity.executor.adapter.out.GetHumidityAdapter;
import ch.unisg.executorhumidity.executor.application.port.out.GetHumidityPort; import ch.unisg.executorhumidity.executor.application.port.out.GetHumidityPort;
import org.eclipse.californium.elements.exception.ConnectorException;
import java.io.IOException;
public class Executor extends ExecutorBase { public class Executor extends ExecutorBase {
private static final Executor executor = new Executor(ExecutorType.HUMIDITY); private static final Executor executor = new Executor(ExecutorType.HUMIDITY, "http://localhost:8087");
private final GetHumidityPort getHumidityPort = new GetHumidityAdapter(); private final GetHumidityPort getHumidityPort = new GetHumidityAdapter();
private Executor(ExecutorType executorType) {super(executorType);} private Executor(ExecutorType executorType, String uri) {
super(executorType, uri);
}
public static Executor getExecutor() {return executor;} public static Executor getExecutor() {return executor;}
@ -22,8 +21,6 @@ public class Executor extends ExecutorBase {
@Override @Override
protected protected
String execution(String input) { String execution(String input) {
//TODO: Fill
String result = getHumidityPort.getHumidity(); String result = getHumidityPort.getHumidity();
return result; return result;

View File

@ -84,8 +84,7 @@
<dependency> <dependency>
<groupId>com.github.Interactions-HSG</groupId> <groupId>com.github.Interactions-HSG</groupId>
<artifactId>wot-td-java</artifactId> <artifactId>wot-td-java</artifactId>
<version>0.1.1</version> <version>master-SNAPSHOT</version>
<scope>compile</scope>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -11,14 +11,6 @@ import ch.unisg.executorrobot.executor.domain.Executor;
public class ExecutorrobotApplication { public class ExecutorrobotApplication {
public static void main(String[] args) { public static void main(String[] args) {
try {
TimeUnit.SECONDS.sleep(40);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SpringApplication.run(ExecutorrobotApplication.class, args); SpringApplication.run(ExecutorrobotApplication.class, args);
Executor.getExecutor(); Executor.getExecutor();
} }

View File

@ -1,42 +0,0 @@
package ch.unisg.executorrobot.executor.adapter.out;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import ch.unisg.executorrobot.executor.application.port.out.DeleteUserFromRobotPort;
@Component
@Primary
public class DeleteUserFromRobotAdapter implements DeleteUserFromRobotPort {
@Override
public boolean deleteUserFromRobot(String key) {
String url = "https://api.interactions.ics.unisg.ch/leubot1/v1.3.4/user/" + key;
var request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.DELETE()
.build();
var client = HttpClient.newHttpClient();
try {
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
}

View File

@ -1,121 +0,0 @@
package ch.unisg.executorrobot.executor.adapter.out;
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.HashMap;
import java.util.Map;
import java.util.Optional;
import ch.unisg.ics.interactions.wot.td.ThingDescription;
import ch.unisg.ics.interactions.wot.td.affordances.ActionAffordance;
import ch.unisg.ics.interactions.wot.td.affordances.Form;
import ch.unisg.ics.interactions.wot.td.clients.TDHttpRequest;
import ch.unisg.ics.interactions.wot.td.clients.TDHttpResponse;
import ch.unisg.ics.interactions.wot.td.io.TDGraphReader;
import ch.unisg.ics.interactions.wot.td.schemas.DataSchema;
import ch.unisg.ics.interactions.wot.td.schemas.ObjectSchema;
import ch.unisg.ics.interactions.wot.td.schemas.StringSchema;
import ch.unisg.ics.interactions.wot.td.security.APIKeySecurityScheme;
import ch.unisg.ics.interactions.wot.td.vocabularies.TD;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import ch.unisg.executorrobot.executor.application.port.out.InstructionToRobotPort;
@Component
@Primary
public class InstructionToRobotAdapter implements InstructionToRobotPort {
@Override
public boolean instructionToRobot(String key) {
String endpoint = "https://api.interactions.ics.unisg.ch/search/searchEngine";
String input = "@prefix dct: <http://purl.org/dc/terms/> . select ?title where { ?title dct:title 'leubot1' }";
var httpRequest = HttpRequest.newBuilder()
.uri(URI.create(endpoint))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(input))
.build();
var client = HttpClient.newHttpClient();
try {
var description = client.send(httpRequest, HttpResponse.BodyHandlers.ofString()).body();
// Parse a TD from a string
ThingDescription td = TDGraphReader.readFromString(ThingDescription.TDFormat.RDF_TURTLE, description);
// Create the payload to be sent with the Http request
Map<String, Object> elbowPayload = new HashMap<>();
elbowPayload.put("http://www.w3.org/2001/XMLSchema#int", 400);
// Get the affordance "setElbow" from the TD
Optional<ActionAffordance> action = td.getActionByName("setElbow");
// Get the first form
if (action.isPresent()) {
Optional<Form> form = action.get().getFirstForm();
// Retrieve the input data schema from the action affordance
Optional<DataSchema> inputSchema = action.get().getInputSchema();
// If a form is found, use it to create and execute the Http request
if (form.isPresent()) {
TDHttpRequest request = new TDHttpRequest(form.get(), TD.invokeAction);
if (inputSchema.isPresent()) {
request.setObjectPayload((ObjectSchema) inputSchema.get(), elbowPayload);
try {
TDHttpResponse response = request.execute();
System.out.println("Received response with status code: " + response.getStatusCode());
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
/*
String putEndpoint = "https://api.interactions.ics.unisg.ch/leubot1/v1.3.0/elbow";
String inputJson = "{ \"value\": 400}";
var request = HttpRequest.newBuilder()
.uri(URI.create(putEndpoint))
.header("Content-Type", "application/json")
.header("X-API-KEY", key)
.PUT(HttpRequest.BodyPublishers.ofString(inputJson))
.build();
var client = HttpClient.newHttpClient();
try {
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.headers());
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
*/
}
}

View File

@ -1,5 +1,6 @@
package ch.unisg.executorrobot.executor.adapter.out; package ch.unisg.executorrobot.executor.adapter.out;
import java.io.IOException; import java.io.IOException;
import java.io.StringReader;
import java.net.URI; import java.net.URI;
import java.net.http.HttpClient; import java.net.http.HttpClient;
import java.net.http.HttpRequest; import java.net.http.HttpRequest;
@ -7,6 +8,11 @@ import java.net.http.HttpResponse;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.TimeUnit;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import ch.unisg.ics.interactions.wot.td.ThingDescription; import ch.unisg.ics.interactions.wot.td.ThingDescription;
import ch.unisg.ics.interactions.wot.td.affordances.ActionAffordance; import ch.unisg.ics.interactions.wot.td.affordances.ActionAffordance;
@ -16,10 +22,19 @@ import ch.unisg.ics.interactions.wot.td.clients.TDHttpResponse;
import ch.unisg.ics.interactions.wot.td.io.TDGraphReader; import ch.unisg.ics.interactions.wot.td.io.TDGraphReader;
import ch.unisg.ics.interactions.wot.td.schemas.DataSchema; import ch.unisg.ics.interactions.wot.td.schemas.DataSchema;
import ch.unisg.ics.interactions.wot.td.schemas.ObjectSchema; import ch.unisg.ics.interactions.wot.td.schemas.ObjectSchema;
import ch.unisg.ics.interactions.wot.td.security.APIKeySecurityScheme;
import ch.unisg.ics.interactions.wot.td.security.SecurityScheme;
import ch.unisg.ics.interactions.wot.td.vocabularies.TD; import ch.unisg.ics.interactions.wot.td.vocabularies.TD;
import ch.unisg.ics.interactions.wot.td.vocabularies.WoTSec;
import org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration; import org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import ch.unisg.executorrobot.executor.application.port.out.UserToRobotPort; import ch.unisg.executorrobot.executor.application.port.out.UserToRobotPort;
@ -32,7 +47,7 @@ public class UserToRobotAdapter implements UserToRobotPort {
String endpoint = "https://api.interactions.ics.unisg.ch/search/searchEngine"; String endpoint = "https://api.interactions.ics.unisg.ch/search/searchEngine";
String input = "@prefix dct: <http://purl.org/dc/terms/> . select ?title where { ?title dct:title 'Mirogate' }"; String input = "@prefix dct: <http://purl.org/dc/terms/> . select ?title where { ?title dct:title 'leubot1' }";
var httpRequest = HttpRequest.newBuilder() var httpRequest = HttpRequest.newBuilder()
.uri(URI.create(endpoint)) .uri(URI.create(endpoint))
@ -43,13 +58,75 @@ public class UserToRobotAdapter implements UserToRobotPort {
var client = HttpClient.newHttpClient(); var client = HttpClient.newHttpClient();
try { try {
var description = client.send(httpRequest, HttpResponse.BodyHandlers.ofString()).body(); String description = client.send(httpRequest, HttpResponse.BodyHandlers.ofString()).body();
String leubot1Uri = null;
String uri = "http://yggdrasil.interactions.ics.unisg.ch/environments/61/workspaces/102/artifacts/leubot1"; DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(new StringReader(description)));
doc.getDocumentElement().normalize();
NodeList results = doc.getElementsByTagName("uri");
for (int temp = 0; temp < results.getLength(); temp += 1) {
Node nNode = results.item(temp);
if (nNode.getTextContent().contains("leubot1")) {
leubot1Uri = nNode.getTextContent();
}
}
if (leubot1Uri == null) {
// TODO implement logic if execution failed
return "ERROR";
}
// Parse a TD from a string // Parse a TD from a string
ThingDescription td = TDGraphReader.readFromURL(ThingDescription.TDFormat.RDF_TURTLE, uri); ThingDescription td = TDGraphReader.readFromURL(ThingDescription.TDFormat.RDF_TURTLE, leubot1Uri);
String apiUrl = getAPIKey(td);
System.out.println("FOUND API URL " + apiUrl);
String apiKey = apiUrl.split("/")[apiUrl.split("/").length-1].split("]")[0];
System.out.println("FOUND KEY " + apiKey);
if(apiKey == null) {
// TODO implement logic if execution failed
return "ERROR";
}
try {
TimeUnit.MILLISECONDS.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!moveRobot(td, apiKey)) {
return "ERROR";
}
try {
TimeUnit.MILLISECONDS.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
delteUserFromRobot(apiUrl);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (SAXException e1) {
e1.printStackTrace();
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
}
return "OK";
}
private String getAPIKey(ThingDescription td) {
// Create the payload to be sent with the HTTP request // Create the payload to be sent with the HTTP request
Map<String, Object> logInPayload = new HashMap<>(); Map<String, Object> logInPayload = new HashMap<>();
logInPayload.put("http://xmlns.com/foaf/0.1/Name", "keanu rahimian"); logInPayload.put("http://xmlns.com/foaf/0.1/Name", "keanu rahimian");
@ -59,66 +136,106 @@ public class UserToRobotAdapter implements UserToRobotPort {
Optional<ActionAffordance> action = td.getActionByName("logIn"); Optional<ActionAffordance> action = td.getActionByName("logIn");
// Get the first form // Get the first form
if (action.isPresent()) { if (action.isEmpty()) {
Optional<Form> form = action.get().getFirstForm(); // TODO implement logic if execution failed
return null;
}
Optional<Form> form = action.get().getFirstFormForOperationType(TD.invokeAction);
if (form.isEmpty()) {
// TODO implement logic if execution failed
return null;
}
// If a form is found, use it to create and execute the HTTP request
TDHttpRequest request = new TDHttpRequest(form.get(), TD.invokeAction);
// Retrieve the input data schema from the action affordance // Retrieve the input data schema from the action affordance
Optional<DataSchema> inputSchema = action.get().getInputSchema(); Optional<DataSchema> inputSchema = action.get().getInputSchema();
// If a form is found, use it to create and execute the HTTP request
if (form.isPresent()) {
TDHttpRequest request = new TDHttpRequest(form.get(), TD.invokeAction);
if(inputSchema.isPresent()) { if(inputSchema.isPresent()) {
request.setObjectPayload((ObjectSchema) inputSchema.get(), logInPayload); request.setObjectPayload((ObjectSchema) inputSchema.get(), logInPayload);
}
try { try {
TDHttpResponse response = request.execute(); TDHttpResponse response = request.execute();
System.out.println("Received response with status code: " + response.getStatusCode()); System.out.println("Received response with status code: " + response.getStatusCode());
// TODO: Get the key from the response and return it String url = response.getHeaders().get("Location");
// Not exactly sure how to get the headers from the payload, as we need them return url;
// to get the key
} catch (IOException e) {
e.printStackTrace();
}
return null; return null;
}
private boolean moveRobot(ThingDescription td, String key) {
// Create the payload to be sent with the Http request
Map<String, Object> elbowPayload = new HashMap<>();
elbowPayload.put("value", 400);
// Get the affordance "setElbow" from the TD
Optional<ActionAffordance> action = td.getActionByName("setElbow");
// Get the first form
if (action.isEmpty()) {
return false;
}
Optional<Form> form = action.get().getFirstFormForOperationType(TD.invokeAction);
if (form.isEmpty()) {
// TODO implement logic if execution failed
return false;
}
// Retrieve the input data schema from the action affordance
Optional<DataSchema> inputSchema = action.get().getInputSchema();
TDHttpRequest request = new TDHttpRequest(form.get(), TD.invokeAction);
if(inputSchema.isPresent()) {
request.setObjectPayload((ObjectSchema) inputSchema.get(), elbowPayload);
}
Optional<SecurityScheme> securityScheme = td.getFirstSecuritySchemeByType(WoTSec.APIKeySecurityScheme);
if (securityScheme.isPresent()) {
request.setAPIKey((APIKeySecurityScheme) securityScheme.get(), key);
}
try {
TDHttpResponse response = request.execute();
System.out.println("Received response with status code: " + response.getStatusCode());
return true;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
/* return false;
String inputJson = "{ \"name\":\"keanu rahimian\", \"email\":\"keanu.rahimian@student.unisg.ch\"}"; }
var request = HttpRequest.newBuilder()
.uri(URI.create(postEndpoint)) private void delteUserFromRobot(String apiUrl) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.header("Content-Type", "application/json") .header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(inputJson)) .DELETE()
.build(); .build();
HttpClient client = HttpClient.newHttpClient();
try { try {
var response = client.send(request, HttpResponse.BodyHandlers.ofString()); var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode()); System.out.println(response.statusCode());
System.out.println(response.headers());
String url = response.headers().map().get("location").toString();
String key = url.split("/")[url.split("/").length-1].split("]")[0];
return key;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
return null;
*/
return null;
} }
} }

View File

@ -1,5 +0,0 @@
package ch.unisg.executorrobot.executor.application.port.out;
public interface DeleteUserFromRobotPort {
boolean deleteUserFromRobot(String key);
}

View File

@ -1,5 +0,0 @@
package ch.unisg.executorrobot.executor.application.port.out;
public interface InstructionToRobotPort {
boolean instructionToRobot(String key);
}

View File

@ -1,52 +1,28 @@
package ch.unisg.executorrobot.executor.domain; package ch.unisg.executorrobot.executor.domain;
import java.util.concurrent.TimeUnit;
import ch.unisg.executorrobot.executor.adapter.out.DeleteUserFromRobotAdapter;
import ch.unisg.executorrobot.executor.adapter.out.InstructionToRobotAdapter;
import ch.unisg.executorrobot.executor.adapter.out.UserToRobotAdapter; import ch.unisg.executorrobot.executor.adapter.out.UserToRobotAdapter;
import ch.unisg.executorrobot.executor.application.port.out.DeleteUserFromRobotPort;
import ch.unisg.executorrobot.executor.application.port.out.InstructionToRobotPort;
import ch.unisg.executorrobot.executor.application.port.out.UserToRobotPort; import ch.unisg.executorrobot.executor.application.port.out.UserToRobotPort;
import ch.unisg.executorbase.executor.domain.ExecutorBase; import ch.unisg.executorbase.executor.domain.ExecutorBase;
import ch.unisg.executorbase.executor.domain.ExecutorType; import ch.unisg.executorbase.executor.domain.ExecutorType;
public class Executor extends ExecutorBase { public class Executor extends ExecutorBase {
private static final Executor executor = new Executor(ExecutorType.ROBOT); private static final Executor executor = new Executor(ExecutorType.SMALLROBOT, "http://localhost:8084");
private final UserToRobotPort userToRobotPort = new UserToRobotAdapter(); private final UserToRobotPort userToRobotPort = new UserToRobotAdapter();
private final InstructionToRobotPort instructionToRobotPort = new InstructionToRobotAdapter();
private final DeleteUserFromRobotPort deleteUserFromRobotPort = new DeleteUserFromRobotAdapter();
public static Executor getExecutor() { public static Executor getExecutor() {
return executor; return executor;
} }
private Executor(ExecutorType executorType) { private Executor(ExecutorType executorType, String uri) {
super(executorType); super(executorType, uri);
} }
@Override @Override
protected protected
String execution(String input) { String execution(String input) {
userToRobotPort.userToRobot();
String key = userToRobotPort.userToRobot(); return "";
try {
TimeUnit.MILLISECONDS.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean result1 = instructionToRobotPort.instructionToRobot(key);
try {
TimeUnit.MILLISECONDS.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
deleteUserFromRobotPort.deleteUserFromRobot(key);
return Boolean.toString(result1);
} }
} }

View File

@ -25,6 +25,9 @@ public class PublishNewTaskEventAdapter implements NewTaskEventPort {
@Value("${executor.computation.uri}") @Value("${executor.computation.uri}")
private String server2; private String server2;
@Value("${executor.humidity.uri}")
private String server3;
Logger logger = Logger.getLogger(PublishNewTaskEventAdapter.class.getName()); Logger logger = Logger.getLogger(PublishNewTaskEventAdapter.class.getName());
/** /**
@ -34,21 +37,21 @@ public class PublishNewTaskEventAdapter implements NewTaskEventPort {
@Override @Override
public void publishNewTaskEvent(NewTaskEvent event) { public void publishNewTaskEvent(NewTaskEvent event) {
// HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
// HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
// .uri(URI.create(server + "/newtask/" + event.taskType.getValue())) .uri(URI.create(server + "/newtask/" + event.taskType.getValue()))
// .GET() .GET()
// .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);
// } }
HttpClient client2 = HttpClient.newHttpClient(); HttpClient client2 = HttpClient.newHttpClient();
HttpRequest request2 = HttpRequest.newBuilder() HttpRequest request2 = HttpRequest.newBuilder()
@ -65,6 +68,22 @@ public class PublishNewTaskEventAdapter implements NewTaskEventPort {
} catch (IOException e) { } catch (IOException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e); logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
} }
HttpClient client3 = HttpClient.newHttpClient();
HttpRequest request3 = HttpRequest.newBuilder()
.uri(URI.create(server3 + "/newtask/" + event.taskType.getValue()))
.GET()
.build();
try {
client3.send(request3, 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

@ -8,6 +8,7 @@ import java.net.http.HttpResponse;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
@ -32,19 +33,22 @@ public class PublishTaskAssignedEventAdapter implements TaskAssignedEventPort {
@Override @Override
public void publishTaskAssignedEvent(TaskAssignedEvent event) { public void publishTaskAssignedEvent(TaskAssignedEvent event) {
String body = new JSONObject() try {
.put("taskId", event.taskID)
.toString(); JSONObject op1 = new JSONObject()
.put("op", "replace")
.put("path", "/taskStatus")
.put("value", "ASSIGNED");
String body = new JSONArray().put(op1).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/" + event.taskID))
.header("Content-Type", "application/task+json") .header("Content-Type", "application/task+json")
.POST(HttpRequest.BodyPublishers.ofString(body)) .method("PATCH", HttpRequest.BodyPublishers.ofString(body))
.build(); .build();
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);
@ -52,6 +56,28 @@ public class PublishTaskAssignedEventAdapter implements TaskAssignedEventPort {
} catch (IOException e) { } catch (IOException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e); logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
} }
// 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/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);
// }
} }
} }

View File

@ -8,6 +8,7 @@ import java.net.http.HttpResponse;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
@ -32,21 +33,27 @@ public class PublishTaskCompletedEventAdapter implements TaskCompletedEventPort
@Override @Override
public void publishTaskCompleted(TaskCompletedEvent event) { public void publishTaskCompleted(TaskCompletedEvent event) {
String body = new JSONObject() try {
.put("taskId", event.taskID)
.put("status", event.status) JSONObject op1 = new JSONObject()
.put("outputData", event.result) .put("op", "replace")
.toString(); .put("path", "/taskStatus")
.put("value", event.status);
JSONObject op2 = new JSONObject()
.put("op", "replace")
.put("path", "/outputData")
.put("value", event.result);
String body = new JSONArray().put(op1).put(op2).toString();
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/" + event.taskID))
.header("Content-Type", "application/task+json") .header("Content-Type", "application/task+json")
.POST(HttpRequest.BodyPublishers.ofString(body)) .method("PATCH", HttpRequest.BodyPublishers.ofString(body))
.build(); .build();
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);
@ -55,6 +62,29 @@ public class PublishTaskCompletedEventAdapter implements TaskCompletedEventPort
logger.log(Level.SEVERE, e.getLocalizedMessage(), e); logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
} }
// String body = new JSONObject()
// .put("taskId", event.taskID)
// .put("status", event.status)
// .put("outputData", event.result)
// .toString();
// HttpClient client = HttpClient.newHttpClient();
// HttpRequest request = HttpRequest.newBuilder()
// .uri(URI.create(server + "/tasks/completeTask/"))
// .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);
// }
} }
} }

View File

@ -4,6 +4,10 @@ import ch.unisg.tapas.auctionhouse.adapter.common.clients.TapasMqttClient;
import ch.unisg.tapas.auctionhouse.adapter.in.messaging.mqtt.AuctionEventsMqttDispatcher; import ch.unisg.tapas.auctionhouse.adapter.in.messaging.mqtt.AuctionEventsMqttDispatcher;
import ch.unisg.tapas.auctionhouse.adapter.common.clients.WebSubSubscriber; import ch.unisg.tapas.auctionhouse.adapter.common.clients.WebSubSubscriber;
import ch.unisg.tapas.auctionhouse.application.service.GetExecutorsService; import ch.unisg.tapas.auctionhouse.application.service.GetExecutorsService;
import ch.unisg.tapas.auctionhouse.domain.AuctionHouseDiscovery;
import ch.unisg.tapas.auctionhouse.domain.AuctionHouseDiscoveryInformation;
import ch.unisg.tapas.common.AuctionHouseResourceDirectory;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttException;
@ -13,6 +17,9 @@ import org.springframework.core.env.ConfigurableEnvironment;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/** /**
* Main TAPAS Auction House application. * Main TAPAS Auction House application.
@ -30,7 +37,7 @@ public class TapasAuctionHouseApplication {
ENVIRONMENT = tapasAuctioneerApp.run(args).getEnvironment(); ENVIRONMENT = tapasAuctioneerApp.run(args).getEnvironment();
// TODO Set start up of message services with config // TODO Set start up of message services with config
// We will use these bootstrap methods in Week 6: // We will use these bootstrap methods in Week 6:
// bootstrapMarketplaceWithWebSub(); bootstrapMarketplaceWithWebSub();
bootstrapMarketplaceWithMqtt(); bootstrapMarketplaceWithMqtt();
var getExecutorsService = new GetExecutorsService(); var getExecutorsService = new GetExecutorsService();
getExecutorsService.getExecutorsFromExecutorPool(); getExecutorsService.getExecutorsFromExecutorPool();
@ -39,20 +46,23 @@ public class TapasAuctionHouseApplication {
* Discovers auction houses and subscribes to WebSub notifications * Discovers auction houses and subscribes to WebSub notifications
*/ */
private static void bootstrapMarketplaceWithWebSub() { private static void bootstrapMarketplaceWithWebSub() {
// discoverAuctionHouseEndpoints(); discoverAuctionHouseEndpoints();
WebSubSubscriber subscriber = new WebSubSubscriber(ENVIRONMENT.getProperty("auction.house.uri")); WebSubSubscriber subscriber = new WebSubSubscriber(ENVIRONMENT.getProperty("auction.house.uri"));
// for (AuctionHouseDiscoveryInformation endpoint : AuctionHouseDiscovery.getInstance().getAuctionHouseDiscoveryList()) { for (AuctionHouseDiscoveryInformation endpoint : AuctionHouseDiscovery.getInstance().getAuctionHouseDiscoveryList()) {
// subscriber.subscribeToAuctionHouseEndpoint(endpoint.getWebSubUri().getValue()); // Don't subscribe to our own auction house
// } if (!endpoint.getWebSubUri().getValue().toString().equalsIgnoreCase("https://tapas-auction-house.86-119-35-40.nip.io/websub/auctions")) {
try { subscriber.subscribeToAuctionHouseEndpoint(endpoint.getWebSubUri().getValue());
subscriber.subscribeToAuctionHouseEndpoint(new URI("http://6b4e-130-82-250-227.ngrok.io/websub-discovery"));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
} }
// try {
// subscriber.subscribeToAuctionHouseEndpoint(new URI("http://6b4e-130-82-250-227.ngrok.io/websub-discovery"));
// } catch (URISyntaxException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
/** /**
* Connects to an MQTT broker, presumably the one used by all TAPAS groups to communicate with * Connects to an MQTT broker, presumably the one used by all TAPAS groups to communicate with
@ -76,17 +86,17 @@ public class TapasAuctionHouseApplication {
} }
} }
// private static void discoverAuctionHouseEndpoints() { private static void discoverAuctionHouseEndpoints() {
// AuctionHouseResourceDirectory rd = new AuctionHouseResourceDirectory( AuctionHouseResourceDirectory rd = new AuctionHouseResourceDirectory(
// URI.create(ENVIRONMENT.getProperty("discovery.endpoint.uri")) URI.create(ENVIRONMENT.getProperty("discovery.endpoint.uri"))
// ); );
// AuctionHouseDiscovery.getInstance().addAuctionHouseDiscoveryInformation(rd.retrieveAuctionHouseEndpoints()); AuctionHouseDiscovery.getInstance().addAuctionHouseDiscoveryInformation(rd.retrieveAuctionHouseEndpoints());
// ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// executor.scheduleAtFixedRate(crawlerRunnable, 300, 300, TimeUnit.SECONDS); // executor.scheduleAtFixedRate(crawlerRunnable, 300, 300, TimeUnit.SECONDS);
// } }
// private static Runnable crawlerRunnable = new Runnable() { // private static Runnable crawlerRunnable = new Runnable() {

View File

@ -101,6 +101,9 @@ public class WebSubSubscriber {
return; return;
} }
System.out.println("HUB: " + hub);
System.out.println("TOPIC: " + topic);
HttpRequest request = HttpRequest.newBuilder() HttpRequest request = HttpRequest.newBuilder()
.uri(hubURI) .uri(hubURI)
.header("Content-Type", "application/x-www-form-urlencoded") .header("Content-Type", "application/x-www-form-urlencoded")

View File

@ -22,11 +22,9 @@ import java.net.http.HttpResponse;
public class ExternalAuctionStartedEventListenerMqttAdapter extends AuctionEventMqttListener{ public class ExternalAuctionStartedEventListenerMqttAdapter extends AuctionEventMqttListener{
private static final Logger LOGGER = LogManager.getLogger(ExternalAuctionStartedEventListenerMqttAdapter.class); private static final Logger LOGGER = LogManager.getLogger(ExternalAuctionStartedEventListenerMqttAdapter.class);
// String auctionHouseURI = "https://tapas-auction-house.86-119-35-40.nip.io/"; String auctionHouseURI = "https://tapas-auction-house.86-119-35-40.nip.io/";
String auctionHouseURI = "http://a888-77-59-152-182.eu.ngrok.io";
// String taskListURI = "https://tapas-tasks.86-119-35-40.nip.io"; String taskListURI = "https://tapas-tasks.86-119-35-40.nip.io";
String taskListURI = "http://e021-77-59-152-182.ngrok.io";
@Override @Override
public boolean handleEvent(MqttMessage message){ public boolean handleEvent(MqttMessage message){

View File

@ -69,11 +69,9 @@ public class AuctionStartedEventListenerWebSubAdapter {
// } // }
// String auctionHouseURI = "https://tapas-auction-house.86-119-35-40.nip.io/"; String auctionHouseURI = "https://tapas-auction-house.86-119-35-40.nip.io/";
String auctionHouseURI = "http://b311-130-82-247-153.eu.ngrok.io";
// String taskListURI = "https://tapas-tasks.86-119-35-40.nip.io"; String taskListURI = "https://tapas-tasks.86-119-35-40.nip.io";
String taskListURI = "http://c64f-130-82-247-153.ngrok.io";
// TODO Sanitize URIs // TODO Sanitize URIs
String auctionId = auction.getString("auctionId"); String auctionId = auction.getString("auctionId");

View File

@ -30,7 +30,7 @@ public class AuctionHouseDiscoveryWebController {
this.auctionHouseDiscoveryUseCase = auctionHouseDiscoveryUseCase; this.auctionHouseDiscoveryUseCase = auctionHouseDiscoveryUseCase;
} }
@GetMapping(path="/discovery/", consumes = AuctionHouseDiscoveryJsonRepresentation.MEDIA_TYPE) @GetMapping(path="/discovery/")
public ResponseEntity<String> auctionHouseDiscovery() { public ResponseEntity<String> auctionHouseDiscovery() {
List<AuctionHouseDiscoveryInformation> auctionHouseDiscoveryInformation = auctionHouseDiscoveryUseCase.auctionHouseDiscovery(); List<AuctionHouseDiscoveryInformation> auctionHouseDiscoveryInformation = auctionHouseDiscoveryUseCase.auctionHouseDiscovery();

View File

@ -27,9 +27,11 @@ public class WinningBidWebController {
@PostMapping(path = "/taskwinner", consumes = TaskJsonRepresentation.MEDIA_TYPE) @PostMapping(path = "/taskwinner", consumes = TaskJsonRepresentation.MEDIA_TYPE)
public ResponseEntity<String> winningBid(@RequestBody TaskJsonRepresentation payload){ public ResponseEntity<String> winningBid(@RequestBody TaskJsonRepresentation payload){
LOGGER.info("New Task Winner");
try { try {
var body = payload.serialize(); var body = payload.serialize();
LOGGER.info(body); LOGGER.info("Task Winner body: " + body);
LOGGER.info("Task Winner taskListURI: " + taskListURI);
var postURI = URI.create(taskListURI + "/tasks/"); var postURI = URI.create(taskListURI + "/tasks/");
HttpRequest postRequest = HttpRequest.newBuilder() HttpRequest postRequest = HttpRequest.newBuilder()
.uri(postURI) .uri(postURI)
@ -40,7 +42,7 @@ public class WinningBidWebController {
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();
var postResponse = client.send(postRequest, HttpResponse.BodyHandlers.ofString()); var postResponse = client.send(postRequest, HttpResponse.BodyHandlers.ofString());
LOGGER.info(postResponse.statusCode()); LOGGER.info("Create task internally with status code: " + postResponse.statusCode());
HttpHeaders responseHeaders = new HttpHeaders(); HttpHeaders responseHeaders = new HttpHeaders();

View File

@ -32,6 +32,7 @@ public class PublishAuctionStartedEventWebSubAdapter implements AuctionStartedEv
@Override @Override
public void publishAuctionStartedEvent(AuctionStartedEvent event) { public void publishAuctionStartedEvent(AuctionStartedEvent event) {
logger.info("AuctionHouse | Publish auction started over WebSub!"); logger.info("AuctionHouse | Publish auction started over WebSub!");
logger.info("AuctionHouse | AuctionHouseURI: " + auctionHouseUri + " WebSubHubUri: " + webSubHubUri);
HttpClient client = HttpClient.newHttpClient(); HttpClient client = HttpClient.newHttpClient();

View File

@ -6,6 +6,7 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.springframework.http.HttpStatus;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
@ -22,16 +23,16 @@ public class AuctionHouseDiscoveryHttpAdapter implements AuctionHouseDiscoveryPo
public List<AuctionHouseDiscoveryInformation> fetchAuctionHouseInformation(URI auctionHouseURI){ public List<AuctionHouseDiscoveryInformation> fetchAuctionHouseInformation(URI auctionHouseURI){
System.out.println(auctionHouseURI);
try{ try{
var client = HttpClient.newHttpClient(); var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder() var request = HttpRequest.newBuilder()
.uri(auctionHouseURI) .uri(auctionHouseURI)
.GET() .GET()
.build(); .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString()); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
LOGGER.info(response.body()); LOGGER.info("Response status code: " + response.statusCode());
LOGGER.info("Response body:" + response.body());
if (response.statusCode() == HttpStatus.OK.value()) {
var responseBody = new JSONObject(response.body()); var responseBody = new JSONObject(response.body());
var arrayOfInformation = responseBody.getJSONArray("auctionHouseInfo"); var arrayOfInformation = responseBody.getJSONArray("auctionHouseInfo");
@ -41,8 +42,8 @@ public class AuctionHouseDiscoveryHttpAdapter implements AuctionHouseDiscoveryPo
{ {
var informationJSON = arrayOfInformation.getJSONObject(i); var informationJSON = arrayOfInformation.getJSONObject(i);
var information = new AuctionHouseDiscoveryInformation( var information = new AuctionHouseDiscoveryInformation(
new AuctionHouseDiscoveryInformation.AuctionHouseUri(URI.create(informationJSON.getString("auctionHouseURI"))), new AuctionHouseDiscoveryInformation.AuctionHouseUri(URI.create(informationJSON.getString("auctionHouseUri"))),
new AuctionHouseDiscoveryInformation.WebSubUri(URI.create(informationJSON.getString("webSubURI"))), new AuctionHouseDiscoveryInformation.WebSubUri(URI.create(informationJSON.getString("webSubUri"))),
new AuctionHouseDiscoveryInformation.TaskTypes(getTaskTypes(informationJSON.getJSONArray("taskTypes"))), new AuctionHouseDiscoveryInformation.TaskTypes(getTaskTypes(informationJSON.getJSONArray("taskTypes"))),
new AuctionHouseDiscoveryInformation.TimeStamp(Timestamp.valueOf(informationJSON.getString("timeStamp"))), new AuctionHouseDiscoveryInformation.TimeStamp(Timestamp.valueOf(informationJSON.getString("timeStamp"))),
new AuctionHouseDiscoveryInformation.GroupName(informationJSON.getString("groupName")) new AuctionHouseDiscoveryInformation.GroupName(informationJSON.getString("groupName"))
@ -51,7 +52,8 @@ public class AuctionHouseDiscoveryHttpAdapter implements AuctionHouseDiscoveryPo
} }
return returnList; return returnList;
}
return Collections.<AuctionHouseDiscoveryInformation>emptyList();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return Collections.<AuctionHouseDiscoveryInformation>emptyList(); return Collections.<AuctionHouseDiscoveryInformation>emptyList();

View File

@ -52,13 +52,18 @@ public class AuctionWonEventHttpAdapter implements AuctionWonEventPort {
LOGGER.info(response.body()); LOGGER.info(response.body());
JSONObject responseBody = new JSONObject(response.body()); JSONObject responseBody = new JSONObject(response.body());
String inputData = "";
if (!responseBody.isNull("inputData")) {
inputData = responseBody.getString("inputData");
}
var task = new Task( var task = new Task(
new Task.TaskName(responseBody.getString("taskName")), new Task.TaskName(responseBody.getString("taskName")),
new Task.TaskType(responseBody.getString("taskType")), new Task.TaskType(responseBody.getString("taskType")),
new Task.OriginalTaskUri(auction.get().getTaskUri().getValue().toString()), new Task.OriginalTaskUri(auction.get().getTaskUri().getValue().toString()),
new Task.TaskStatus(ch.unisg.tapas.auctionhouse.domain.Task.Status.ASSIGNED), new Task.TaskStatus(ch.unisg.tapas.auctionhouse.domain.Task.Status.ASSIGNED),
new Task.TaskId(responseBody.getString("taskId")), new Task.TaskId(responseBody.getString("taskId")),
new Task.InputData(responseBody.getString("inputData")), new Task.InputData(inputData),
new Task.ServiceProvider("TODO") new Task.ServiceProvider("TODO")
); );

View File

@ -65,8 +65,17 @@ public class StartAuctionService implements LaunchAuctionUseCase {
auctions.addAuction(auction); auctions.addAuction(auction);
// Schedule the closing of the auction at the deadline // Schedule the closing of the auction at the deadline
System.out.println(deadline.getValue().getTime());
System.out.println(System.currentTimeMillis());
System.out.println(deadline.getValue().getTime() - System.currentTimeMillis());
if (deadline.getValue().getTime() == DEFAULT_AUCTION_DEADLINE_MILLIS.getTime()) {
System.out.println("DEFAULT TIMESTAMP USED");
service.schedule(new CloseAuctionTask(auction.getAuctionId()), 10000,
TimeUnit.MILLISECONDS);
} else {
service.schedule(new CloseAuctionTask(auction.getAuctionId()), deadline.getValue().getTime() - System.currentTimeMillis(), service.schedule(new CloseAuctionTask(auction.getAuctionId()), deadline.getValue().getTime() - System.currentTimeMillis(),
TimeUnit.MILLISECONDS); TimeUnit.MILLISECONDS);
}
// Publish an auction started event // Publish an auction started event
AuctionStartedEvent auctionStartedEvent = new AuctionStartedEvent(auction); AuctionStartedEvent auctionStartedEvent = new AuctionStartedEvent(auction);

View File

@ -15,8 +15,9 @@ public class AuctionHouseDiscovery {
private final List<String> tasktypes = new ArrayList<String>() { private final List<String> tasktypes = new ArrayList<String>() {
{ {
add("computation"); add("COMPUTATION");
add("smallrobot"); add("SMALLROBOT");
add("HUMIDITY");
} }
}; };
@ -31,8 +32,8 @@ public class AuctionHouseDiscovery {
try { try {
// Add our information to list // Add our information to list
auctionHouseDiscoveryList.add(new AuctionHouseDiscoveryInformation( auctionHouseDiscoveryList.add(new AuctionHouseDiscoveryInformation(
new AuctionHouseDiscoveryInformation.AuctionHouseUri(new URI("http://localhost:8086")), new AuctionHouseDiscoveryInformation.AuctionHouseUri(new URI("https://tapas-auction-house.86-119-35-40.nip.io")),
new AuctionHouseDiscoveryInformation.WebSubUri(new URI("http://localhost:8086/websub/auctions")), new AuctionHouseDiscoveryInformation.WebSubUri(new URI("https://tapas-auction-house.86-119-35-40.nip.io/websub/auctions")),
new AuctionHouseDiscoveryInformation.TaskTypes(tasktypes), new AuctionHouseDiscoveryInformation.TaskTypes(tasktypes),
new AuctionHouseDiscoveryInformation.TimeStamp(new Timestamp(new Date().getTime())), new AuctionHouseDiscoveryInformation.TimeStamp(new Timestamp(new Date().getTime())),
new AuctionHouseDiscoveryInformation.GroupName("Group 1") new AuctionHouseDiscoveryInformation.GroupName("Group 1")

View File

@ -7,7 +7,6 @@ websub.hub.publish=https://websub.appspot.com/
group=tapas-group-1 group=tapas-group-1
auction.house.uri=https://tapas-auction-house.86-119-35-40.nip.io auction.house.uri=https://tapas-auction-house.86-119-35-40.nip.io
# auction.house.uri=http://a888-77-59-152-182.eu.ngrok.io
tasks.list.uri=http://localhost:8081 tasks.list.uri=http://localhost:8081
application.environment=development application.environment=development
@ -15,4 +14,4 @@ websub.hub.uri=https://pubsubhubbub.appspot.com
mqtt.broker.uri=tcp://broker.hivemq.com mqtt.broker.uri=tcp://broker.hivemq.com
# mqtt.broker.uri=tcp://localhost:1883 # mqtt.broker.uri=tcp://localhost:1883
discovery.endpoint.uri=http://localhost:3500 discovery.endpoint.uri=https://tapas-auction-house.86-119-34-242.nip.io

View File

@ -43,7 +43,7 @@ public class ExternalTaskExecutedWebAdapter implements ExternalTaskExecutedEvent
op2 = new JSONObject() op2 = new JSONObject()
.put("op", "add") .put("op", "add")
.put("path", "/outputData") .put("path", "/outputData")
.put("value", externalTaskExecutedEvent.getOutputData()); .put("value", externalTaskExecutedEvent.getOutputData().getValue());
} catch (JSONException e) { } catch (JSONException e) {
logger.log(Level.SEVERE, e.getLocalizedMessage(), e); logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
return; return;

View File

@ -2,7 +2,7 @@ server.port=8081
spring.data.mongodb.uri=mongodb://root:password@localhost:27017/ spring.data.mongodb.uri=mongodb://root:password@localhost:27017/
spring.data.mongodb.database=tapas-tasks spring.data.mongodb.database=tapas-tasks
# baseuri=http://e021-77-59-152-182.ngrok.io/ # baseuri=http://e021-77-59-152-182.ngrok.io/
baseuri=https://tapas-tasks.86-119-34-23.nip.io/ baseuri=https://tapas-tasks.86-119-35-40.nip.io/
roster.uri=http://127.0.0.1:8082 roster.uri=http://127.0.0.1:8082