This commit is contained in:
2021-12-19 16:33:11 +01:00
parent 0022ebaf88
commit 0eb21d2083
15 changed files with 225 additions and 305 deletions

View File

@@ -82,11 +82,10 @@
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.Interactions-HSG</groupId>
<artifactId>wot-td-java</artifactId>
<version>0.1.1</version>
<scope>compile</scope>
</dependency>
<groupId>com.github.Interactions-HSG</groupId>
<artifactId>wot-td-java</artifactId>
<version>master-SNAPSHOT</version>
</dependency>
</dependencies>
<build>

View File

@@ -11,14 +11,6 @@ import ch.unisg.executorrobot.executor.domain.Executor;
public class ExecutorrobotApplication {
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);
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;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
@@ -7,6 +8,11 @@ import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
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.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.schemas.DataSchema;
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.WoTSec;
import org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration;
import org.springframework.context.annotation.Primary;
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;
@@ -32,7 +47,7 @@ public class UserToRobotAdapter implements UserToRobotPort {
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()
.uri(URI.create(endpoint))
@@ -43,82 +58,184 @@ public class UserToRobotAdapter implements UserToRobotPort {
var client = HttpClient.newHttpClient();
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)));
// Parse a TD from a string
ThingDescription td = TDGraphReader.readFromURL(ThingDescription.TDFormat.RDF_TURTLE, uri);
doc.getDocumentElement().normalize();
// Create the payload to be sent with the HTTP request
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/Mbox", "keanu.rahimian@student.unisg.ch");
// Get the affordance "Log-In" from the TD
Optional<ActionAffordance> action = td.getActionByName("logIn");
// 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(), logInPayload);
try {
TDHttpResponse response = request.execute();
System.out.println("Received response with status code: " + response.getStatusCode());
// TODO: Get the key from the response and return it
// Not exactly sure how to get the headers from the payload, as we need them
// to get the key
return null;
} catch (IOException e) {
e.printStackTrace();
}
}
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
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
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/Mbox", "keanu.rahimian@student.unisg.ch");
// Get the affordance "Log-In" from the TD
Optional<ActionAffordance> action = td.getActionByName("logIn");
// Get the first form
if (action.isEmpty()) {
// TODO implement logic if execution failed
return null;
}
/*
String inputJson = "{ \"name\":\"keanu rahimian\", \"email\":\"keanu.rahimian@student.unisg.ch\"}";
var request = HttpRequest.newBuilder()
.uri(URI.create(postEndpoint))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(inputJson))
.build();
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
Optional<DataSchema> inputSchema = action.get().getInputSchema();
if(inputSchema.isPresent()) {
request.setObjectPayload((ObjectSchema) inputSchema.get(), logInPayload);
}
try {
TDHttpResponse response = request.execute();
System.out.println("Received response with status code: " + response.getStatusCode());
String url = response.getHeaders().get("Location");
return url;
} catch (IOException e) {
e.printStackTrace();
}
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) {
e.printStackTrace();
}
return false;
}
private void delteUserFromRobot(String apiUrl) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.header("Content-Type", "application/json")
.DELETE()
.build();
HttpClient client = HttpClient.newHttpClient();
try {
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
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) {
e.printStackTrace();
} catch (InterruptedException e) {
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,22 +1,14 @@
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.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.executorbase.executor.domain.ExecutorBase;
import ch.unisg.executorbase.executor.domain.ExecutorType;
public class Executor extends ExecutorBase {
private static final Executor executor = new Executor(ExecutorType.ROBOT);
private static final Executor executor = new Executor(ExecutorType.SMALLROBOT);
private final UserToRobotPort userToRobotPort = new UserToRobotAdapter();
private final InstructionToRobotPort instructionToRobotPort = new InstructionToRobotAdapter();
private final DeleteUserFromRobotPort deleteUserFromRobotPort = new DeleteUserFromRobotAdapter();
public static Executor getExecutor() {
return executor;
@@ -29,24 +21,7 @@ public class Executor extends ExecutorBase {
@Override
protected
String execution(String input) {
String key = userToRobotPort.userToRobot();
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);
return userToRobotPort.userToRobot();
}
}