using fr_emac_gind_model;
using gind_csharp_driver_examples_test;
using gind_csharp_driver_rest;
using gind_csharp_driver_rest_app;
using gind_csharp_driver_rest_listeners;
using gind_csharp_driver_rest_listeners_models;
using gind_csharp_model;
using gind_csharp_utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace gind_csharp_driver_examples_test_examples
{
public class IMT_CGI_Crisis_Example : IUCExample
{
public IMT_CGI_Crisis_Example(string dns_address) : base(dns_address)
{
}
public IMT_CGI_Crisis_Example(Program.IOptions options) : base(options)
{
}
public IMT_CGI_Crisis_Example(string configFile, int ignore) : base(configFile, ignore)
{
}
public IMT_CGI_Crisis_Example(string host, int rioda_port, int riose_port, int rioxo_port, int riota_port) : base(host, rioda_port, riose_port, rioxo_port, riota_port)
{
}
public override string getCollaborationName()
{
return "R-IO Suite WorkSpace";
}
public override string getKnowledgeSpaceName()
{
return "IMT CGI Crisis";
}
public override async Task<bool> run()
{
// test
RestDriver driver = createRestDriver(SystemUser.DEFAULT_ADMIN);
Console.WriteLine("Rest driver version: " + driver.getVersion());
Console.WriteLine("Rest driver creation date: " + driver.getCreationDate());
Console.WriteLine("Rest driver unity compatiblity version: " + driver.getUnityVersion());
Thread.Sleep(2000);
// We suppose that:
// - R-IO is started
// - The default administrator is already connected
// - The usecase is loaded
Console.WriteLine("\n\nLoad usecase:");
completeUsecaseDefinition usecaseDefinition = await driver.metaModelDriver.findPredefinedUsecaseDefinitionByName(getKnowledgeSpaceName());
UsecaseContext usecaseContext = await driver.metaModelDriver.loadUsecase(usecaseDefinition, getCollaborationName());
Console.WriteLine("\tusecase loaded");
driver.metaModelDriver.setProjectMode(ProjectMode.Real);
Console.WriteLine("\treal mode set on project");
// Model api: push, pushpull, reload
// Example with push
Console.WriteLine("\n\nModel API:");
Console.WriteLine("\tpush model");
driver.modelDriver.push(new genericModel()
{
node = new node[1]
{
new node()
{
id = "node-" + Util.generateUUID(),
status = new statusType[1] { statusType.ACTIVE },
type = new XmlQualifiedName("Potentiality", "http://fr.emac.gind/collaborative-model"),
property = new property[1]
{
new property()
{
name = "name",
value = "Risk_1"
}
}
}
}
});
Console.WriteLine("\tmodel pushed");
Console.WriteLine("\ttest query");
node[] danger = await driver.modelDriver.getNodesByTypesAndOrProperties(new XmlQualifiedName[1] { new XmlQualifiedName("Potential", "http://fr.emac.gind/collaborative-model") });
genericModel all_model = await driver.modelDriver.query("match (n:instance:`{http://fr.emac.gind/collaborative-model}Potential`) return n");
Console.WriteLine("\t=> nodes: " + (all_model.node != null ? all_model.node.Length : 0) + " - " + " edges: " + (all_model.edge != null ? all_model.edge.Length : 0));
Console.WriteLine("\t=> query realized");
Console.WriteLine("\tmodel api done");
// 5 bis: subscribe to model modification
MyWSockAddNodeEventFunction addNodeEventFunction = new MyWSockAddNodeEventFunction(driver, this);
usecaseContext.addWSockFunction(addNodeEventFunction);
MyWSockRemoveNodeEventFunction removeNodeEventFunction = new MyWSockRemoveNodeEventFunction(driver, this);
usecaseContext.addWSockFunction(removeNodeEventFunction);
usecaseContext.startWSockUsecaseChannel();
// Event API
Console.WriteLine("\n\nEvent API:");
RealSensor[] sensors = await driver.eventDriver.findSensorsByProtocol(Protocol.JSON_Connector);
bool resStart = await driver.eventDriver.startSensors(sensors);
RealSensor firstSmokeSensor = sensors[0];
Console.WriteLine("\tSend smoke event to: " + firstSmokeSensor.getName());
bool resEvent = await driver.eventDriver.sendEventOnJSONConnector(firstSmokeSensor, position: new position1() { Item = new point() { latitude = 0.44f, longitude = 0.63f } }, smokeEvent: new dataSmoke() { value = true });
bool resStop = await driver.eventDriver.stopSensors(sensors);
Console.WriteLine("\tevent api done");
// UserTask API (part 1/2)
Console.WriteLine("\n\nUserTask API:");
List<AppUser> app_users = await driver.appUserTaskDriver.refreshUsers();
AppUser adminUser = driver.appUserTaskDriver.findUserById(SystemUser.DEFAULT_ADMIN.getNodeId());
MyProcessResponseWSockFunction myProcessResponseWSockFunction = new MyProcessResponseWSockFunction();
MyProcessCancelWSockFunction myProcessCancelWSockFunction = new MyProcessCancelWSockFunction();
adminUser.affectTaskBehaviours(new List<AppWSockUserFunction>() { new MyUserTodoListener(), myProcessResponseWSockFunction, myProcessCancelWSockFunction });
bool login = await adminUser.login();
List<AppTask> adminUser_tasks = await adminUser.refreshTodoList();
Console.WriteLine("\tnumber of tasks: " + adminUser_tasks.Count);
// Process API
Console.WriteLine("\n\nProcess API:");
node[] objectives = await driver.modelDriver.getNodesByTypesAndOrProperties(new XmlQualifiedName[1] { new XmlQualifiedName("Objective", "http://fr.emac.gind/collaborative-model") });
Console.WriteLine("\tobjectives: " + objectives.Length);
if (objectives != null && objectives.Length > 0)
{
Console.WriteLine("\tStart process deduction... ");
deductionReport[] reports = await driver.processDriver.deduce(new SatisfactionStrategy(objectives));
Console.WriteLine("\tprocess deduction achieved");
deductionResult process_result = (deductionResult)reports[0].Item;
Console.WriteLine("\tDeploy process... ");
genericModel process_model = process_result.genericModel;
node[] processNodes = GenericModelUtil.getNodesByType(new XmlQualifiedName("Process", "http://fr.emac.gind/collaborative-model"), process_model);
node processNode = processNodes[0];
DeployResult deployResult = await driver.processDriver.deploy(processNode);
RunProcessRequest request = new RunProcessRequest()
{
sampledProcess = new sampledProcess()
{
id = processNode.id,
name = PropertyUtil.findPropertyByName("name", processNode.property).value
},
endpointAddress = deployResult.endpointAddress,
requestHeaderContext = new RequestHeaderContext()
{
onlyCurrentUser = true
}
};
Console.WriteLine("\tprocess surpervised");
string processInstanceId = await driver.processDriver.runASync(request, null);
addNodeEventFunction.setProcessInstanceId(processInstanceId);
removeNodeEventFunction.setProcessInstanceId(processInstanceId);
Console.WriteLine("\tprocess started");
bool superviseResp = await driver.processDriver.supervise(processInstanceId);
MyMonitoringExchangeWSockFunction myMonitoringWSockFunction = new MyMonitoringExchangeWSockFunction();
bool subscribeResp = await driver.processDriver.subscribeExchangesByInstance(processInstanceId, myMonitoringWSockFunction);
Console.WriteLine("\tsubscription achieved");
exchange[] existingExchanges = await driver.processDriver.exchangesByInstance(processInstanceId);
Console.WriteLine("\texisting exchanges: " + existingExchanges.Length);
while (this.processIsRunning(myMonitoringWSockFunction))
{
adminUser_tasks = await adminUser.refreshTodoList();
Console.WriteLine("\tnumber of tasks: " + adminUser_tasks.Count);
Console.WriteLine("\tprocessIsRunning: " + this.processIsRunning(myMonitoringWSockFunction));
foreach (AppTask task in adminUser_tasks)
{
if(task.status != StatusType1.DONE)
{
adminUser.updateTask(task, StatusType1.DONE);
}
}
Thread.Sleep(500);
}
// wait detection achieved
Thread.Sleep(1000);
while (myProcessResponseWSockFunction.ProcessEnded == false && myProcessCancelWSockFunction.ProcessCancel == false)
{
Console.WriteLine("Wait detection achieved !!!");
Thread.Sleep(500);
}
Console.WriteLine("\tprocess ended or cancelled");
bool resDelete = await driver.processDriver.delete(processInstanceId);
// bool resUndeploy = await driver.processDriver.undeploy(deployResult);
}
Console.WriteLine("\tprocess api done");
// UserTask API (part 2/2)
// netsh http add urlacl url=http://*:4444/user_id_admin_1/ user=${userName}
/**
toDoResponse resp = await this.sendTestTODOAt(adminUser, new toDo()
{
task = new task()
{
name = "task_2",
taskId = "task_2"
}
});
while (adminUser_tasks.Count == 0)
{
Console.WriteLine("\tnumber of tasks after send: " + adminUser_tasks.Count);
Console.WriteLine("Sleep for 2 seconds.");
Thread.Sleep(2000);
}
Console.WriteLine("\tnumber of tasks after send: " + adminUser_tasks.Count);
bool logout = await adminUser.logout();
Console.WriteLine("\tuserTask api done");
*/
Console.WriteLine("IMT CGI CRISIS FINISHED !!!");
return true;
}
private bool processIsRunning(MyMonitoringExchangeWSockFunction myMonitoringWSockFunction)
{
if (myMonitoringWSockFunction.getCurrentProcessProgressionEvent() != null && myMonitoringWSockFunction.getCurrentProcessProgressionEvent().monitoringInstanceProgression != null && (myMonitoringWSockFunction.getCurrentProcessProgressionEvent().monitoringInstanceProgression.currentStep ==
myMonitoringWSockFunction.getCurrentProcessProgressionEvent().monitoringInstanceProgression.totalSteps))
{
myMonitoringWSockFunction.getCurrentProcessProgressionEvent().monitoringInstanceProgression.processStatus = ProcessStatusType.ENDED;
}
if (myMonitoringWSockFunction.getCurrentProcessProgressionEvent() == null || myMonitoringWSockFunction.getCurrentProcessProgressionEvent().monitoringInstanceProgression == null || myMonitoringWSockFunction.getCurrentProcessProgressionEvent().monitoringInstanceProgression.processStatus == ProcessStatusType.RUNNING
|| myMonitoringWSockFunction.getCurrentProcessProgressionEvent().monitoringInstanceProgression.processStatus == ProcessStatusType.CREATED)
{
return true;
}
return false;
}
/**
private async Task<toDoResponse> sendTestTODOAt(AppUser user, toDo req)
{
HttpClient client = new HttpClient();
req.userId = user.getId();
Console.WriteLine("send task: " + req.task.taskId + " for user: " + user.getId());
var content = new StringContent(JSONMarshaller.marshall<toDo>(req), Encoding.UTF8, "application/json");
HttpResponseMessage httpResponseMessage = await client.PostAsync(user.getTaskListener().callbackAddress, content);
string buffer = await httpResponseMessage.Content.ReadAsStringAsync();
if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
{
throw new Exception(httpResponseMessage.StatusCode + ": " + buffer);
}
toDoResponse resp = JSONMarshaller.unmarshall<toDoResponse>(buffer);
return resp;
}
*/
public class MyUserTodoListener : AppWSockTODOFunction
{
public MyUserTodoListener() : base()
{
}
public override void onReceiveTask(AppTask newTask)
{
Console.WriteLine("receive new task: " + newTask.getId() + " for user: " + this.user.getId());
}
}
public class MyMonitoringExchangeWSockFunction : WSockMonitoringExchangeProgressionEvent
{
monitoringProcessInstanceProgressionEvent currentProcessProgression = null;
public MyMonitoringExchangeWSockFunction() : base()
{
}
public override void onReceiveMonitoringProcessInstanceProgressionEvent(monitoringProcessInstanceProgressionEvent mpipe)
{
Console.WriteLine("monitoring exchange received !!!");
this.currentProcessProgression = mpipe;
}
public monitoringProcessInstanceProgressionEvent getCurrentProcessProgressionEvent()
{
return this.currentProcessProgression;
}
}
public class MyProcessResponseWSockFunction : WSockProcessResponseFunction
{
bool processEnded = false;
public MyProcessResponseWSockFunction() : base()
{
}
public bool ProcessEnded { get => processEnded; set => processEnded = value; }
public override void onReceiveProcessResponse(sendASyncResponse response)
{
Console.WriteLine("process response received !!!");
processEnded = true;
}
}
public class MyProcessCancelWSockFunction : WSockProcessCancelFunction
{
bool processCancel = false;
public MyProcessCancelWSockFunction() : base()
{
}
public bool ProcessCancel { get => processCancel; set => processCancel = value; }
public override void onCancel(cancel cancel)
{
Console.WriteLine("process cancel received !!!");
processCancel = true;
}
}
public class MyWSockAddNodeEventFunction : WSockAddNodeEvent
{
RestDriver driver;
string processInstanceId;
IUCExample uc;
public MyWSockAddNodeEventFunction(RestDriver driver, IUCExample uc) : base()
{
this.driver = driver;
this.uc = uc;
}
public override void onAddNodeEvent(addNodeEvent response)
{
Console.WriteLine("onAddNodeEvent received !!!");
Task task = this.uc.detectCriticalDivergenceOnNodeAsync(response.node, IUCExample.Action.ADD, driver, processInstanceId);
}
public void setProcessInstanceId(string processInstanceId)
{
this.processInstanceId = processInstanceId;
}
}
public class MyWSockRemoveNodeEventFunction : WSockRemoveNodeEvent
{
RestDriver driver;
string processInstanceId;
IUCExample uc;
public MyWSockRemoveNodeEventFunction(RestDriver driver, IUCExample uc) : base()
{
this.driver = driver;
this.uc = uc;
}
public override void onRemoveNodeEvent(removeNodeEvent response)
{
Console.WriteLine("onRemoveNodeEvent received !!!");
Task task = this.uc.detectCriticalDivergenceOnNodeAsync(response.node, IUCExample.Action.ADD, driver, processInstanceId);
}
public void setProcessInstanceId(string processInstanceId)
{
this.processInstanceId = processInstanceId;
}
}
}
}
|