use of won.bot.framework.eventbot.event.impl.atomlifecycle.AtomCreatedEvent in project webofneeds by researchstudio-sat.
the class CreateAtomAction method doRun.
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
EventListenerContext ctx = getEventListenerContext();
BotContextWrapper botContextWrapper = ctx.getBotContextWrapper();
if (ctx.getAtomProducer().isExhausted()) {
logger.info("the bot's atom producer is exhausted.");
ctx.getEventBus().publish(new AtomProducerExhaustedEvent());
return;
}
final Dataset atomDataset = ctx.getAtomProducer().create();
if (atomDataset == null) {
logger.warn("atomproducer failed to produce an atom model, aborting atom creation");
return;
}
URI atomUriFromProducer = null;
Resource atomResource = WonRdfUtils.AtomUtils.getAtomResource(atomDataset);
if (atomResource.isURIResource()) {
atomUriFromProducer = URI.create(atomResource.getURI());
RdfUtils.replaceBaseURI(atomDataset, atomResource.getURI(), true);
} else {
RdfUtils.replaceBaseResource(atomDataset, atomResource, true);
}
final URI atomUriBeforeCreation = atomUriFromProducer;
AtomModelWrapper atomModelWrapper = new AtomModelWrapper(atomDataset);
final Dataset atomDatasetWithSockets = atomModelWrapper.copyDatasetWithoutSysinfo();
final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
logger.debug("creating atom on won node {} with content {} ", wonNodeUri, StringUtils.abbreviate(RdfUtils.toString(Prefixer.setPrefixes(atomDatasetWithSockets)), 150));
WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService();
final URI atomURI = wonNodeInformationService.generateAtomURI(wonNodeUri);
WonMessage createAtomMessage = createWonMessage(atomURI, atomDatasetWithSockets);
createAtomMessage = ctx.getWonMessageSender().prepareMessage(createAtomMessage);
// remember the atom URI so we can react to success/failure responses
botContextWrapper.rememberAtomUri(atomURI);
EventListener successCallback = event12 -> {
logger.debug("atom creation successful, new atom URI is {}", atomURI);
ctx.getEventBus().publish(new AtomCreatedEvent(atomURI, wonNodeUri, atomDatasetWithSockets, null, atomUriBeforeCreation));
};
EventListener failureCallback = event1 -> {
String textMessage = WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) event1).getFailureMessage());
logger.debug("atom creation failed for atom URI {}, original message URI {}: {}", new Object[] { atomURI, ((FailureResponseEvent) event1).getOriginalMessageURI(), textMessage });
botContextWrapper.removeAtomUri(atomURI);
ctx.getEventBus().publish(new AtomCreationFailedEvent(wonNodeUri, atomUriBeforeCreation));
};
EventBotActionUtils.makeAndSubscribeResponseListener(createAtomMessage, successCallback, failureCallback, ctx);
logger.debug("registered listeners for response to message URI {}", createAtomMessage.getMessageURI());
ctx.getWonMessageSender().sendMessage(createAtomMessage);
logger.debug("atom creation message sent with message URI {}", createAtomMessage.getMessageURI());
}
use of won.bot.framework.eventbot.event.impl.atomlifecycle.AtomCreatedEvent in project webofneeds by researchstudio-sat.
the class CreateAtomWithSocketsAction method doRun.
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
EventListenerContext ctx = getEventListenerContext();
if (ctx.getAtomProducer().isExhausted()) {
logger.info("the bot's atom producer is exhausted.");
ctx.getEventBus().publish(new AtomProducerExhaustedEvent());
return;
}
final Dataset atomDataset = ctx.getAtomProducer().create();
if (atomDataset == null) {
logger.warn("atomproducer failed to produce an atom model, aborting atom creation");
return;
}
URI atomUriFromProducer = null;
Resource atomResource = WonRdfUtils.AtomUtils.getAtomResource(atomDataset);
if (atomResource.isURIResource()) {
atomUriFromProducer = URI.create(atomResource.getURI());
RdfUtils.replaceBaseURI(atomDataset, atomResource.getURI(), true);
} else {
RdfUtils.replaceBaseResource(atomDataset, atomResource, true);
}
final URI atomUriBeforeCreation = atomUriFromProducer;
AtomModelWrapper atomModelWrapper = new AtomModelWrapper(atomDataset);
int i = 1;
for (URI socket : sockets) {
atomModelWrapper.addSocket(atomUriBeforeCreation.toString() + "#socket" + i, socket.toString());
i++;
}
final Dataset atomDatasetWithSockets = atomModelWrapper.copyDatasetWithoutSysinfo();
final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
logger.debug("creating atom on won node {} with content {} ", wonNodeUri, StringUtils.abbreviate(RdfUtils.toString(Prefixer.setPrefixes(atomDatasetWithSockets)), 150));
WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService();
final URI atomURI = wonNodeInformationService.generateAtomURI(wonNodeUri);
WonMessage createAtomMessage = createWonMessage(atomURI, wonNodeUri, atomDatasetWithSockets);
createAtomMessage = ctx.getWonMessageSender().prepareMessage(createAtomMessage);
// remember the atom URI so we can react to success/failure responses
ctx.getBotContextWrapper().rememberAtomUri(atomURI);
EventListener successCallback = event12 -> {
logger.debug("atom creation successful, new atom URI is {}", atomURI);
ctx.getEventBus().publish(new AtomCreatedEvent(atomURI, wonNodeUri, atomDatasetWithSockets, null, atomUriBeforeCreation));
};
EventListener failureCallback = event1 -> {
String textMessage = WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) event1).getFailureMessage());
logger.debug("atom creation failed for atom URI {}, original message URI {}: {}", new Object[] { atomURI, ((FailureResponseEvent) event1).getOriginalMessageURI(), textMessage });
ctx.getBotContextWrapper().removeAtomUri(atomURI);
ctx.getEventBus().publish(new AtomCreationFailedEvent(wonNodeUri, atomUriBeforeCreation));
};
EventBotActionUtils.makeAndSubscribeResponseListener(createAtomMessage, successCallback, failureCallback, ctx);
logger.debug("registered listeners for response to message URI {}", createAtomMessage.getMessageURI());
ctx.getWonMessageSender().sendMessage(createAtomMessage);
logger.debug("atom creation message sent with message URI {}", createAtomMessage.getMessageURI());
}
use of won.bot.framework.eventbot.event.impl.atomlifecycle.AtomCreatedEvent in project webofneeds by researchstudio-sat.
the class ServiceAtomBehaviour method onActivate.
@Override
protected void onActivate(Optional<Object> message) {
logger.debug("activating ServiceAtomBehaviour");
final EventListenerContext ctx = this.context;
subscribeWithAutoCleanup(InitializeEvent.class, new ActionOnEventListener(ctx, new AbstractCreateAtomAction(ctx) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
logger.debug("Initializing the BotServiceAtom...");
URI serviceAtomUri = serviceAtomContext.getServiceAtomUri();
if (serviceAtomUri == null) {
logger.debug("BotServiceAtom does not exist, creating a new one...");
createServiceAtom();
} else {
logger.debug("BotServiceAtom exists atomUri: {} checking validity...", serviceAtomUri);
Dataset serviceBotDataSet = ctx.getLinkedDataSource().getDataForPublicResource(serviceAtomUri);
if (serviceBotDataSet == null) {
logger.debug("BotServiceAtom can't be retrieved, creating a new one...");
createServiceAtom();
} else {
ServiceAtomModelWrapper oldServiceAtomWrapper = new ServiceAtomModelWrapper(serviceBotDataSet);
if (!Objects.equals(oldServiceAtomWrapper.getServiceAtomContent(), serviceAtomContent)) {
logger.debug("BotServiceAtom is outdated, modifying the BotServiceAtom");
modifyServiceAtom(oldServiceAtomWrapper);
} else {
logger.info("#####################################################################################");
logger.info("BotServiceAtom is still up to date, atom URI is {}", serviceAtomUri);
logger.info("#####################################################################################");
}
}
}
}
private void createServiceAtom() {
final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService();
final URI atomUri = wonNodeInformationService.generateAtomURI(wonNodeUri);
Dataset botServiceDataset = new ServiceAtomModelWrapper(atomUri, serviceAtomContent).copyDataset();
logger.debug("creating BotServiceAtom on won node {} with content: {} ", wonNodeUri, RdfUtils.toString(Prefixer.setPrefixes(botServiceDataset)));
WonMessage createAtomMessage = createWonMessage(atomUri, botServiceDataset);
createAtomMessage = ctx.getWonMessageSender().prepareMessage(createAtomMessage);
ctx.getBotContextWrapper().rememberAtomUri(atomUri);
EventBus bus = ctx.getEventBus();
EventListener successCallback = event -> {
logger.info("#####################################################################################");
logger.info("BotServiceAtom creation successful, new atom URI is {}", atomUri);
logger.info("#####################################################################################");
serviceAtomContext.setServiceAtomUri(atomUri);
bus.publish(new AtomCreatedEvent(atomUri, wonNodeUri, botServiceDataset, null));
};
EventListener failureCallback = event -> {
String textMessage = WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) event).getFailureMessage());
logger.error("BotServiceAtom creation failed for atom URI {}, original message URI: {}", atomUri, textMessage);
ctx.getBotContextWrapper().removeAtomUri(atomUri);
};
EventBotActionUtils.makeAndSubscribeResponseListener(createAtomMessage, successCallback, failureCallback, ctx);
logger.debug("registered listeners for response to message URI {}", createAtomMessage.getMessageURI());
ctx.getWonMessageSender().sendMessage(createAtomMessage);
logger.debug("BotServiceAtom creation message sent with message URI {}", createAtomMessage.getMessageURI());
}
private void modifyServiceAtom(ServiceAtomModelWrapper oldServiceAtomModelWrapper) {
final URI atomUri = URI.create(oldServiceAtomModelWrapper.getAtomUri());
// Replace placeholder socketUris with existing socketUris
// if socketType was present before modification
Map<String, String> oldServiceAtomSocketsInverse = oldServiceAtomModelWrapper.getServiceAtomContent().getSockets().entrySet().stream().collect(Collectors.toMap(socketEntry -> socketEntry.getValue(), socketEntry -> socketEntry.getKey()));
serviceAtomContent.setSockets(serviceAtomContent.getSockets().entrySet().stream().collect(Collectors.toMap(socketEntry -> oldServiceAtomSocketsInverse.containsKey(socketEntry.getValue()) ? oldServiceAtomSocketsInverse.get(socketEntry.getValue()) : socketEntry.getKey(), socketEntry -> socketEntry.getValue())));
ServiceAtomModelWrapper serviceAtomModelWrapper = new ServiceAtomModelWrapper(atomUri, serviceAtomContent);
final URI wonNodeUri = URI.create(oldServiceAtomModelWrapper.getWonNodeUri());
Dataset botServiceDataset = serviceAtomModelWrapper.copyDataset();
logger.debug("creating BotServiceAtom on won node {} with content: {} ", wonNodeUri, RdfUtils.toString(Prefixer.setPrefixes(botServiceDataset)));
RdfUtils.replaceBaseURI(botServiceDataset, atomUri.toString(), true);
ServiceAtomModelWrapper modifiedAtomModelWrapper = new ServiceAtomModelWrapper(botServiceDataset);
WonMessage modifyAtomMessage = WonMessageBuilder.replace().atom(atomUri).content().dataset(modifiedAtomModelWrapper.copyDatasetWithoutSysinfo()).build();
modifyAtomMessage = ctx.getWonMessageSender().prepareMessage(modifyAtomMessage);
ctx.getBotContextWrapper().rememberAtomUri(atomUri);
EventBus bus = ctx.getEventBus();
EventListener successCallback = event -> {
logger.info("#####################################################################################");
logger.info("BotServiceAtom modification successful, atom URI is {}", atomUri);
logger.info("#####################################################################################");
serviceAtomContext.setServiceAtomUri(atomUri);
bus.publish(new AtomCreatedEvent(atomUri, wonNodeUri, botServiceDataset, null));
};
EventListener failureCallback = event -> {
String textMessage = WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) event).getFailureMessage());
logger.error("BotServiceAtom modification failed for atom URI {}, original message URI: {}", atomUri, textMessage);
ctx.getBotContextWrapper().removeAtomUri(atomUri);
};
EventBotActionUtils.makeAndSubscribeResponseListener(modifyAtomMessage, successCallback, failureCallback, ctx);
logger.debug("registered listeners for response to message URI {}", modifyAtomMessage.getMessageURI());
ctx.getWonMessageSender().sendMessage(modifyAtomMessage);
logger.debug("BotServiceAtom creation message sent with message URI {}", modifyAtomMessage.getMessageURI());
}
}));
subscribeWithAutoCleanup(AtomCreatedEvent.class, new ActionOnEventListener(ctx, new BaseEventBotAction(ctx) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
if (event instanceof AtomCreatedEvent) {
AtomCreatedEvent atomCreatedEvent = (AtomCreatedEvent) event;
URI botServiceAtomUri = serviceAtomContext.getServiceAtomUri();
URI createdAtomUri = atomCreatedEvent.getAtomURI();
if (!Objects.equals(createdAtomUri, botServiceAtomUri)) {
if (ctx.getBotContextWrapper().isAtomKnown(createdAtomUri)) {
logger.debug("Atom ({}) is known, must be one we created..., dataset: {}", createdAtomUri, RdfUtils.toString(Prefixer.setPrefixes(atomCreatedEvent.getAtomDataset())));
Optional<URI> createdAtomHoldableSocketUri = WonLinkedDataUtils.getSocketsOfType(createdAtomUri, WXHOLD.HoldableSocket.asURI(), ctx.getLinkedDataSource()).stream().findFirst();
if (createdAtomHoldableSocketUri.isPresent()) {
logger.debug("Atom ({}) has the holdableSocket, connect botServiceAtom ({}) with this atom", createdAtomUri, botServiceAtomUri);
Optional<URI> botServiceAtomHolderSocketUri = WonLinkedDataUtils.getSocketsOfType(botServiceAtomUri, WXHOLD.HolderSocket.asURI(), ctx.getLinkedDataSource()).stream().findFirst();
logger.debug("Connecting atom ({}) - botServiceAtom ({})", createdAtomUri, botServiceAtomUri);
URI senderSocketURI = createdAtomHoldableSocketUri.orElseThrow(() -> new IllegalStateException("no suitable socket for connecting on created atom " + createdAtomUri));
URI recipientSocketURI = botServiceAtomHolderSocketUri.orElseThrow(() -> new IllegalStateException("no suitable socket for connecting on bot service atom " + botServiceAtomUri));
WonMessage connectToServiceAtomMessage = WonMessageBuilder.connect().sockets().sender(senderSocketURI).recipient(recipientSocketURI).content().text("Automated Connect to Service Atom").build();
ctx.getWonMessageSender().prepareAndSendMessage(connectToServiceAtomMessage);
} else {
logger.debug("Atom ({}) does not have a holdable Socket, no connect action required", createdAtomUri);
}
} else {
logger.debug("Atom ({}) is not known, must be someone elses...", createdAtomUri);
}
} else {
logger.debug("BotServiceAtomCreated, no connect action required");
}
}
}
}));
subscribeWithAutoCleanup(ConnectFromOtherAtomEvent.class, new ActionOnEventListener(ctx, new BaseEventBotAction(ctx) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
if (event instanceof ConnectFromOtherAtomEvent) {
ConnectFromOtherAtomEvent connectFromOtherAtomEvent = (ConnectFromOtherAtomEvent) event;
URI botServiceAtomUri = serviceAtomContext.getServiceAtomUri();
URI senderAtomUri = connectFromOtherAtomEvent.getWonMessage().getSenderAtomURI();
URI targetAtomUri = connectFromOtherAtomEvent.getWonMessage().getRecipientAtomURI();
logger.debug("Possibly accept the connection Request with holderFacet<->holdableFacet if atom is BotServiceAtom");
if (ctx.getBotContextWrapper().isAtomKnown(senderAtomUri) && ctx.getBotContextWrapper().isAtomKnown(targetAtomUri) && Objects.equals(targetAtomUri, botServiceAtomUri)) {
logger.debug("Both Atoms belong to you, you might want to accept the connect, socketUri: {}, targetSocketUri: {}", connectFromOtherAtomEvent.getWonMessage().getSenderSocketURI(), connectFromOtherAtomEvent.getWonMessage().getRecipientSocketURI());
URI senderSocketUri = connectFromOtherAtomEvent.getWonMessage().getSenderSocketURI();
URI targetSocketUri = connectFromOtherAtomEvent.getWonMessage().getRecipientSocketURI();
Optional<URI> senderSocketTypeUri = WonLinkedDataUtils.getTypeOfSocket(senderSocketUri, ctx.getLinkedDataSource());
Optional<URI> targetSocketTypeUri = WonLinkedDataUtils.getTypeOfSocket(targetSocketUri, ctx.getLinkedDataSource());
if (senderSocketTypeUri.isPresent() && targetSocketTypeUri.isPresent() && Objects.equals(senderSocketTypeUri.get(), WXHOLD.HoldableSocket.asURI()) && Objects.equals(targetSocketTypeUri.get(), WXHOLD.HolderSocket.asURI())) {
logger.debug("Accepting connect request from atom ({}) to serviceAtom ({})", senderAtomUri, targetAtomUri);
WonMessage openServiceAtomMessage = WonMessageBuilder.connect().sockets().reactingTo(connectFromOtherAtomEvent.getWonMessage()).direction().fromOwner().content().text("Automated Open from Service Atom").build();
ctx.getWonMessageSender().prepareAndSendMessage(openServiceAtomMessage);
}
} else {
logger.debug("At least one of the two Atoms is not known, or the targetAtomUri is not the botServiceAtomUri, ignore the connect request");
}
}
}
}));
}
use of won.bot.framework.eventbot.event.impl.atomlifecycle.AtomCreatedEvent in project webofneeds by researchstudio-sat.
the class MatchingLoadTestMonitorAction method doRun.
@Override
protected void doRun(final Event event, EventListener executingListener) throws Exception {
Stopwatch stopwatch = SimonManager.getStopwatch("atomHintFullRoundtrip");
if (event instanceof AtomCreatedEvent) {
Split split = stopwatch.start();
atomSplits.put(((AtomCreatedEvent) event).getAtomURI().toString(), split);
logger.info("RECEIVED EVENT {} for uri {}", event, ((AtomCreatedEvent) event).getAtomURI().toString());
long startTime = System.currentTimeMillis();
String atomUri = ((AtomCreatedEvent) event).getAtomURI().toString();
atomEventStartTime.put(atomUri, startTime);
} else if (event instanceof AtomHintFromMatcherEvent) {
String atomUri = ((AtomHintFromMatcherEvent) event).getRecipientAtom().toString();
logger.info("RECEIVED EVENT {} for uri {}", event, atomUri);
long hintReceivedTime = System.currentTimeMillis();
atomSplits.get(atomUri).stop();
hintEventReceivedTime.computeIfAbsent(atomUri, k -> new LinkedList<>());
hintEventReceivedTime.get(atomUri).add(hintReceivedTime);
} else if (event instanceof SocketHintFromMatcherEvent) {
String atomUri = ((SocketHintFromMatcherEvent) event).getRecipientSocket().toString();
logger.info("RECEIVED EVENT {} for uri {}", event, atomUri);
long hintReceivedTime = System.currentTimeMillis();
atomSplits.get(atomUri).stop();
hintEventReceivedTime.computeIfAbsent(atomUri, k -> new LinkedList<>());
hintEventReceivedTime.get(atomUri).add(hintReceivedTime);
}
if (startTestTime == -1) {
startTestTime = System.currentTimeMillis();
}
logger.info("Number of Atoms: {}", atomEventStartTime.size());
logger.info("Number of Hints: {}", getTotalHints());
logger.info("Number of Atoms with Hints: {}", getAtomsWithHints());
logger.info("Average Duration: {}", getAverageHintDuration());
logger.info("Minimum Duration: {}", getMinHintDuration());
logger.info("Maximum Duration: {}", getMaxHintDuration());
logger.info("Atoms with Hints per Second: {}", getAtomsWithAtomsPerSecond(startTestTime));
logger.info("Hints per Second: {}", getHintsPerSecondThroughput(startTestTime));
}
Aggregations