use of won.bot.framework.eventbot.action.BaseEventBotAction in project webofneeds by researchstudio-sat.
the class InitFactoryAction method doRun.
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
if (!(event instanceof InitializeEvent) || !(getEventListenerContext().getBotContextWrapper() instanceof FactoryBotContextWrapper)) {
logger.error("InitFactoryAction can only handle InitializeEvent with FactoryBotContextWrapper");
return;
}
final boolean usedForTesting = this.usedForTesting;
final boolean doNotMatch = this.doNotMatch;
EventListenerContext ctx = getEventListenerContext();
EventBus bus = ctx.getEventBus();
FactoryBotContextWrapper botContextWrapper = (FactoryBotContextWrapper) ctx.getBotContextWrapper();
// create a targeted counter that will publish an event when the target is reached
// in this case, 0 unfinished need creations means that all needs were created
final TargetCounterDecorator creationUnfinishedCounter = new TargetCounterDecorator(ctx, new CounterImpl("creationUnfinished"), 0);
BotTrigger createFactoryNeedTrigger = new BotTrigger(ctx, Duration.ofMillis(FACTORYNEEDCREATION_DURATION_INMILLIS));
createFactoryNeedTrigger.activate();
bus.subscribe(StartFactoryNeedCreationEvent.class, new ActionOnFirstEventListener(ctx, new PublishEventAction(ctx, new StartBotTriggerCommandEvent(createFactoryNeedTrigger))));
bus.subscribe(BotTriggerEvent.class, new ActionOnTriggerEventListener(ctx, createFactoryNeedTrigger, new BaseEventBotAction(ctx) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
if (isTooManyMessagesInFlight(messagesInFlightCounter)) {
return;
}
adjustTriggerInterval(createFactoryNeedTrigger, messagesInFlightCounter);
// defined via spring
NeedProducer needProducer = ctx.getNeedProducer();
Dataset dataset = needProducer.create();
if (dataset == null && needProducer.isExhausted()) {
bus.publish(new NeedProducerExhaustedEvent());
bus.unsubscribe(executingListener);
return;
}
URI needUriFromProducer = null;
Resource needResource = WonRdfUtils.NeedUtils.getNeedResource(dataset);
if (needResource.isURIResource()) {
needUriFromProducer = URI.create(needResource.getURI());
}
if (needUriFromProducer != null) {
URI needURI = botContextWrapper.getURIFromInternal(needUriFromProducer);
if (needURI != null) {
bus.publish(new FactoryNeedCreationSkippedEvent());
} else {
bus.publish(new CreateNeedCommandEvent(dataset, botContextWrapper.getFactoryListName(), usedForTesting, doNotMatch));
}
}
}
}));
bus.subscribe(CreateNeedCommandSuccessEvent.class, new ActionOnEventListener(ctx, new MultipleActions(ctx, // decrease the creationUnfinishedCounter
new DecrementCounterAction(ctx, creationUnfinishedCounter), // count a successful need creation
new IncrementCounterAction(ctx, needCreationSuccessfulCounter), new BaseEventBotAction(ctx) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
if (event instanceof CreateNeedCommandSuccessEvent) {
CreateNeedCommandSuccessEvent needCreatedEvent = (CreateNeedCommandSuccessEvent) event;
botContextWrapper.addInternalIdToUriReference(needCreatedEvent.getNeedUriBeforeCreation(), needCreatedEvent.getNeedURI());
}
}
})));
bus.subscribe(CreateNeedCommandEvent.class, new ActionOnEventListener(ctx, new MultipleActions(ctx, // execute the need creation for the need in the event
new ExecuteCreateNeedCommandAction(ctx), // increase the needCreationStartedCounter to signal another pending creation
new IncrementCounterAction(ctx, needCreationStartedCounter), // increase the creationUnfinishedCounter to signal another pending creation
new IncrementCounterAction(ctx, creationUnfinishedCounter))));
// if a need is already created we skip the recreation of it and increase the needCreationSkippedCounter
bus.subscribe(FactoryNeedCreationSkippedEvent.class, new ActionOnEventListener(ctx, new IncrementCounterAction(ctx, needCreationSkippedCounter)));
// if a creation failed, we don't want to keep us from keeping the correct count
bus.subscribe(CreateNeedCommandFailureEvent.class, new ActionOnEventListener(ctx, new MultipleActions(ctx, // decrease the creationUnfinishedCounter
new DecrementCounterAction(ctx, creationUnfinishedCounter), // count an unsuccessful need creation
new IncrementCounterAction(ctx, needCreationFailedCounter))));
// when the needproducer is exhausted, we stop the creator (trigger) and we have to wait until all unfinished need creations finish
// when they do, the InitFactoryFinishedEvent is published
bus.subscribe(NeedProducerExhaustedEvent.class, new ActionOnFirstEventListener(ctx, new MultipleActions(ctx, new PublishEventAction(ctx, new StopBotTriggerCommandEvent(createFactoryNeedTrigger)), new BaseEventBotAction(ctx) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
// when we're called, there probably are need creations unfinished, but there may not be
// a)
// first, prepare for the case when there are unfinished need creations:
// we register a listener, waiting for the unfinished counter to reach 0
EventListener waitForUnfinishedNeedsListener = new ActionOnFirstEventListener(ctx, new TargetCounterFilter(creationUnfinishedCounter), new PublishEventAction(ctx, new InitFactoryFinishedEvent()));
bus.subscribe(TargetCountReachedEvent.class, waitForUnfinishedNeedsListener);
// now, we can check if we've already reached the target
if (creationUnfinishedCounter.getCount() <= 0) {
// ok, turned out we didn't need that listener
bus.unsubscribe(waitForUnfinishedNeedsListener);
bus.publish(new InitFactoryFinishedEvent());
}
}
})));
bus.subscribe(InitFactoryFinishedEvent.class, new ActionOnFirstEventListener(ctx, "factoryCreateStatsLogger", new BaseEventBotAction(ctx) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
logger.info("FactoryNeedCreation finished: total:{}, successful: {}, failed: {}, skipped: {}", new Object[] { needCreationStartedCounter.getCount(), needCreationSuccessfulCounter.getCount(), needCreationFailedCounter.getCount(), needCreationSkippedCounter.getCount() });
}
}));
// MessageInFlight counter handling *************************
bus.subscribe(MessageCommandEvent.class, new ActionOnEventListener(ctx, new IncrementCounterAction(ctx, messagesInFlightCounter)));
bus.subscribe(MessageCommandResultEvent.class, new ActionOnEventListener(ctx, new DecrementCounterAction(ctx, messagesInFlightCounter)));
// if we receive a message command failure, log it
bus.subscribe(MessageCommandFailureEvent.class, new ActionOnEventListener(ctx, new LogMessageCommandFailureAction(ctx)));
// Start the need creation stuff
bus.publish(new StartFactoryNeedCreationEvent());
}
use of won.bot.framework.eventbot.action.BaseEventBotAction in project webofneeds by researchstudio-sat.
the class FactoryBotInitBehaviour method onActivate.
@Override
protected void onActivate(Optional<Object> message) {
subscribeWithAutoCleanup(InitializeEvent.class, new ActionOnEventListener(context, new InitFactoryAction(context)));
subscribeWithAutoCleanup(InitFactoryFinishedEvent.class, new ActionOnFirstEventListener(context, new BaseEventBotAction(context) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
FactoryBotInitBehaviour.this.deactivate();
}
}));
}
use of won.bot.framework.eventbot.action.BaseEventBotAction in project webofneeds by researchstudio-sat.
the class CrawlConnectionDataBehaviour method onActivate.
@Override
protected void onActivate(Optional<Object> message) {
logger.debug("activating crawling connection data for connection {}", command.getConnectionURI());
logger.debug("will deactivate autmatically after " + abortTimeout);
LinkedDataSource linkedDataSource = context.getLinkedDataSource();
if (linkedDataSource instanceof CachingLinkedDataSource) {
URI toInvalidate = WonLinkedDataUtils.getEventContainerURIforConnectionURI(command.getConnectionURI(), linkedDataSource);
((CachingLinkedDataSource) linkedDataSource).invalidate(toInvalidate);
((CachingLinkedDataSource) linkedDataSource).invalidate(toInvalidate, command.getNeedURI());
URI remoteConnectionUri = WonLinkedDataUtils.getRemoteConnectionURIforConnectionURI(command.getConnectionURI(), linkedDataSource);
toInvalidate = WonLinkedDataUtils.getEventContainerURIforConnectionURI(remoteConnectionUri, linkedDataSource);
((CachingLinkedDataSource) linkedDataSource).invalidate(toInvalidate);
((CachingLinkedDataSource) linkedDataSource).invalidate(toInvalidate, command.getNeedURI());
}
context.getTaskScheduler().schedule(new Runnable() {
@Override
public void run() {
deactivate();
}
}, new Date(System.currentTimeMillis() + abortTimeout.toMillis()));
;
List<Path> propertyPaths = new ArrayList<>();
PrefixMapping pmap = new PrefixMappingImpl();
pmap.withDefaultMappings(PrefixMapping.Standard);
pmap.setNsPrefix("won", WON.getURI());
pmap.setNsPrefix("msg", WONMSG.getURI());
propertyPaths.add(PathParser.parse("won:hasEventContainer", pmap));
propertyPaths.add(PathParser.parse("won:hasEventContainer/rdfs:member", pmap));
CrawlCommandEvent crawlNeedCommandEvent = new CrawlCommandEvent(command.getNeedURI(), command.getNeedURI(), propertyPaths, 10000, 5);
propertyPaths = new ArrayList();
propertyPaths.add(PathParser.parse("won:hasEventContainer", pmap));
propertyPaths.add(PathParser.parse("won:hasEventContainer/rdfs:member", pmap));
propertyPaths.add(PathParser.parse("won:hasEventContainer/rdfs:member/msg:hasCorrespondingRemoteMessage", pmap));
propertyPaths.add(PathParser.parse("won:hasRemoteNeed", pmap));
propertyPaths.add(PathParser.parse("won:hasRemoteNeed/won:hasEventContainer", pmap));
propertyPaths.add(PathParser.parse("won:hasRemoteNeed/won:hasEventContainer/rdfs:member", pmap));
propertyPaths.add(PathParser.parse("won:hasRemoteConnection", pmap));
propertyPaths.add(PathParser.parse("won:hasRemoteConnection/won:hasEventContainer", pmap));
propertyPaths.add(PathParser.parse("won:hasRemoteConnection/won:hasEventContainer/rdfs:member", pmap));
propertyPaths.add(PathParser.parse("won:hasRemoteConnection/won:hasEventContainer/rdfs:member/msg:hasCorrespondingRemoteMessage", pmap));
CrawlCommandEvent crawlConnectionCommandEvent = new CrawlCommandEvent(command.getNeedURI(), command.getConnectionURI(), propertyPaths, 10000, 5);
Dataset crawledData = DatasetFactory.createGeneral();
// add crawlcommand listener
this.subscribeWithAutoCleanup(CrawlCommandEvent.class, new ActionOnEventListener(context, new OrFilter(new SameEventFilter(crawlNeedCommandEvent), new SameEventFilter(crawlConnectionCommandEvent)), new CrawlAction(context)));
// when the first crawl succeeds, start the second
this.subscribeWithAutoCleanup(CrawlCommandSuccessEvent.class, new ActionOnEventListener(context, new CommandResultFilter(crawlNeedCommandEvent), new BaseEventBotAction(context) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
logger.debug("finished crawling need data. ");
Dataset dataset = ((CrawlCommandSuccessEvent) event).getCrawledData();
RdfUtils.addDatasetToDataset(crawledData, dataset);
// now crawl connection data
context.getEventBus().publish(crawlConnectionCommandEvent);
}
}));
// when we're done crawling, validate:
this.subscribeWithAutoCleanup(CrawlCommandSuccessEvent.class, new ActionOnEventListener(context, new CommandResultFilter(crawlConnectionCommandEvent), new BaseEventBotAction(context) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
logger.debug("finished crawling need data for connection {}", command.getConnectionURI());
Dataset dataset = ((CrawlCommandSuccessEvent) event).getCrawledData();
RdfUtils.addDatasetToDataset(crawledData, dataset);
context.getEventBus().publish(new CrawlConnectionCommandSuccessEvent(command, crawledData));
deactivate();
}
}));
// when something goes wrong, abort
this.subscribeWithAutoCleanup(CrawlCommandFailureEvent.class, new ActionOnFirstEventListener(context, new OrFilter(new CommandResultFilter(crawlConnectionCommandEvent), new CommandResultFilter(crawlNeedCommandEvent)), new BaseEventBotAction(context) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
CrawlCommandFailureEvent failureEvent = (CrawlCommandFailureEvent) event;
logger.debug("crawling failed for connection {}, message: {}", command.getConnectionURI(), failureEvent.getMessage());
context.getEventBus().publish(new CrawlConnectionCommandFailureEvent(failureEvent.getMessage(), command));
deactivate();
}
}));
// start crawling the need - connection will be crawled when need crawling is done
context.getEventBus().publish(crawlNeedCommandEvent);
}
use of won.bot.framework.eventbot.action.BaseEventBotAction in project webofneeds by researchstudio-sat.
the class BAAtomicAdditionalParticipantsBaseBot method initializeEventListeners.
@Override
protected void initializeEventListeners() {
final EventListenerContext ctx = getEventListenerContext();
final AdditionalParticipantCoordinatorBotContextWrapper botContextWrapper = (AdditionalParticipantCoordinatorBotContextWrapper) getBotContextWrapper();
final EventBus bus = getEventBus();
logger.info("info1: No of needs: " + noOfNeeds);
// wait for all needs to be created
WaitForNEventsListener allNeedsCreatedListener = new WaitForNEventsListener(ctx, "waitForAllNeedsCreated", noOfNeeds);
bus.subscribe(NeedCreatedEvent.class, allNeedsCreatedListener);
// create needs every trigger execution until noOfNeeds are created
this.participantNeedCreator = new ActionOnEventListener(ctx, "participantCreator", new CreateNeedWithFacetsAction(ctx, botContextWrapper.getParticipantListName(), getParticipantFacetType().getURI()), noOfNonDelayedNeeds - 1);
bus.subscribe(ActEvent.class, this.participantNeedCreator);
// create needs every trigger execution until noOfNeeds are created
this.delayedParticipantNeedCreator = new ActionOnEventListener(ctx, "delayedParticipantCreator", new CreateNeedWithFacetsAction(ctx, botContextWrapper.getParticipantDelayedListName(), getParticipantFacetType().getURI()), noOfDelayedNeeds);
bus.subscribe(ActEvent.class, this.delayedParticipantNeedCreator);
// when done, create one coordinator need
this.coordinatorNeedCreator = new ActionOnEventListener(ctx, "coordinatorCreator", new FinishedEventFilter(participantNeedCreator), new CreateNeedWithFacetsAction(ctx, botContextWrapper.getCoordinatorListName(), getCoordinatorFacetType().getURI()), 1);
bus.subscribe(FinishedEvent.class, this.coordinatorNeedCreator);
final Iterator<BATestBotScript> firstPhasescriptIterator = firstPhaseScripts.iterator();
final Iterator<BATestBotScript> firstPhaseScriptWithDelayIterator = firstPhaseScriptsWithDelay.iterator();
final Iterator<BATestBotScript> secondPhasescriptIterator = secondPhaseScripts.iterator();
// final Iterator<BATestBotScript> secondPhasescriptWithDelayIterator = secondPhaseScripts.iterator();
// make a composite filter, with one filter for each testScriptListener that wait
// for the FinishedEvents the they emit. That filter will be used to shut
// down all needs after all the scriptListeners have finished.
final OrFilter firstPhaseScriptListenerFilter = new OrFilter();
final OrFilter firstPhaseScriptWithDelayListenerFilter = new OrFilter();
final OrFilter secondPhaseScriptListenerFilter = new OrFilter();
// final OrFilter secondPhaseScriptWithDelayListenerFilter = new OrFilter();
// create a callback that gets called immediately before the connection is established
ConnectFromListToListAction.ConnectHook scriptConnectHook = new ConnectFromListToListAction.ConnectHook() {
@Override
public void onConnect(final URI fromNeedURI, final URI toNeedURI) {
// create the listener that will execute the script actions
BATestScriptListener testScriptListener = new BATestScriptListener(ctx, firstPhasescriptIterator.next(), fromNeedURI, toNeedURI, MILLIS_BETWEEN_MESSAGES);
// remember it so we can check its state later
firstPhasetestScriptListeners.add(testScriptListener);
// subscribe it to the relevant events.
bus.subscribe(ConnectFromOtherNeedEvent.class, testScriptListener);
bus.subscribe(OpenFromOtherNeedEvent.class, testScriptListener);
bus.subscribe(MessageFromOtherNeedEvent.class, testScriptListener);
// add a filter that will wait for the FinishedEvent emitted by that listener
// wrap it in an acceptance filter to make extra sure we count each listener only once.
firstPhaseScriptListenerFilter.addFilter(new AcceptOnceFilter(new FinishedEventFilter(testScriptListener)));
// now we create the listener that is only active in the second phase
// remember it so we can check its state later
BATestScriptListener secondPhaseTestScriptListener = new BATestScriptListener(ctx, secondPhasescriptIterator.next(), fromNeedURI, toNeedURI, MILLIS_BETWEEN_MESSAGES);
secondPhasetestScriptListeners.add(secondPhaseTestScriptListener);
secondPhaseScriptListenerFilter.addFilter(new AcceptOnceFilter(new FinishedEventFilter(secondPhaseTestScriptListener)));
}
};
ConnectFromListToListAction.ConnectHook scriptConnectWithDelayHook = new ConnectFromListToListAction.ConnectHook() {
@Override
public void onConnect(final URI fromNeedURI, final URI toNeedURI) {
// create the listener that will execute the script actions
BATestScriptListener testScriptListener = new BATestScriptListener(ctx, firstPhaseScriptWithDelayIterator.next(), fromNeedURI, toNeedURI, MILLIS_BETWEEN_MESSAGES);
// remember it so we can check its state later
firstPhasetestScriptWithDelayListeners.add(testScriptListener);
// subscribe it to the relevant events.
bus.subscribe(ConnectFromOtherNeedEvent.class, testScriptListener);
bus.subscribe(OpenFromOtherNeedEvent.class, testScriptListener);
bus.subscribe(MessageFromOtherNeedEvent.class, testScriptListener);
// add a filter that will wait for the FinishedEvent emitted by that listener
// wrap it in an acceptance filter to make extra sure we count each listener only once.
firstPhaseScriptWithDelayListenerFilter.addFilter(new AcceptOnceFilter(new FinishedEventFilter(testScriptListener)));
// now we create the listener that is only active in the second phase
// remember it so we can check its state later
BATestScriptListener secondPhaseTestScriptListener = new BATestScriptListener(ctx, secondPhasescriptIterator.next(), fromNeedURI, toNeedURI, MILLIS_BETWEEN_MESSAGES);
secondPhasetestScriptListeners.add(secondPhaseTestScriptListener);
secondPhaseScriptListenerFilter.addFilter(new AcceptOnceFilter(new FinishedEventFilter(secondPhaseTestScriptListener)));
}
};
// when done, connect the participants to the coordinator
this.needConnector = new ActionOnEventListener(ctx, "needConnector", new FinishedEventFilter(allNeedsCreatedListener), new ConnectFromListToListAction(ctx, botContextWrapper.getCoordinatorListName(), botContextWrapper.getParticipantListName(), getCoordinatorFacetType().getURI(), getParticipantFacetType().getURI(), MILLIS_BETWEEN_MESSAGES, scriptConnectHook, "Hi!"), 1);
bus.subscribe(FinishedEvent.class, this.needConnector);
// wait until the non-delayed participants are connected and done with their scripts
BaseEventListener waitForNonDelayedConnectsListener = new WaitForNEventsListener(ctx, firstPhaseScriptListenerFilter, noOfNonDelayedNeeds - 1);
bus.subscribe(FinishedEvent.class, waitForNonDelayedConnectsListener);
FinishedEventFilter allNonDelayedConnectedFilter = new FinishedEventFilter(waitForNonDelayedConnectsListener);
this.needConnectorWithDelay = new ActionOnEventListener(ctx, "needConnectorWithDelay", allNonDelayedConnectedFilter, new ConnectFromListToListAction(ctx, botContextWrapper.getCoordinatorListName(), botContextWrapper.getParticipantDelayedListName(), getCoordinatorFacetType().getURI(), getParticipantFacetType().getURI(), MILLIS_BETWEEN_MESSAGES, scriptConnectWithDelayHook, "Hi!"), 1);
// TODO: MAKE THIS SO URI_LIST_NAME_PARTICIPANT_DELAYED "delayedParticipants" works again
bus.subscribe(FinishedEvent.class, this.needConnectorWithDelay);
// for each group member, there are 2 listeners waiting for messages. when they are all finished, we're done.
this.firstPhaseWithDelayDoneListener = new ActionOnceAfterNEventsListener(ctx, "firstPhaseDoneWithDelayListener", firstPhaseScriptWithDelayListenerFilter, noOfDelayedNeeds, new BaseEventBotAction(ctx) {
@Override
protected void doRun(final Event event, EventListener executingListener) throws Exception {
logger.debug("starting second phase");
logger.debug("non-delayed listeners: {}", firstPhasetestScriptListeners.size());
logger.debug("delayed listeners: {}", firstPhasetestScriptWithDelayListeners.size());
Iterator<BATestScriptListener> firstPhaseListeners = firstPhasetestScriptListeners.iterator();
Iterator<BATestScriptListener> firstPhaseWithDelayListeners = firstPhasetestScriptWithDelayListeners.iterator();
Iterator<BATestScriptListener> combinedFirstPhaseListeners = Iterators.concat(firstPhaseListeners, firstPhaseWithDelayListeners);
logger.debug("# of listeners in second phase: {}", secondPhasetestScriptListeners.size());
for (BATestScriptListener listener : secondPhasetestScriptListeners) {
logger.debug("subscribing second phase listener {}", listener);
// subscribe it to the relevant events.
bus.subscribe(MessageFromOtherNeedEvent.class, listener);
bus.subscribe(SecondPhaseStartedEvent.class, listener);
BATestScriptListener correspondingFirstPhaseListener = combinedFirstPhaseListeners.next();
listener.setCoordinatorSideConnectionURI(correspondingFirstPhaseListener.getCoordinatorSideConnectionURI());
listener.setParticipantSideConnectionURI(correspondingFirstPhaseListener.getParticipantSideConnectionURI());
listener.updateFilterForBothConnectionURIs();
bus.publish(new SecondPhaseStartedEvent(correspondingFirstPhaseListener.getCoordinatorURI(), correspondingFirstPhaseListener.getCoordinatorSideConnectionURI(), correspondingFirstPhaseListener.getParticipantURI()));
}
}
});
bus.subscribe(FinishedEvent.class, this.firstPhaseWithDelayDoneListener);
// for each group member, there are 2 listeners waiting for messages. when they are all finished, we're done.
this.scriptsDoneListener = new ActionOnceAfterNEventsListener(ctx, "scriptsDoneListener", secondPhaseScriptListenerFilter, noOfNeeds - 1, new DeactivateAllNeedsOfListAction(ctx, botContextWrapper.getParticipantListName()));
bus.subscribe(FinishedEvent.class, this.scriptsDoneListener);
// When the needs are deactivated, all connections are closed. wait for the close events and signal work done.
this.workDoneSignaller = new ActionOnceAfterNEventsListener(ctx, "workDoneSignaller", noOfNeeds - 1, new SignalWorkDoneAction(ctx));
bus.subscribe(CloseFromOtherNeedEvent.class, this.workDoneSignaller);
}
use of won.bot.framework.eventbot.action.BaseEventBotAction in project webofneeds by researchstudio-sat.
the class ConversationBotMonitored method initializeEventListeners.
@Override
protected void initializeEventListeners() {
EventListenerContext ctx = getEventListenerContext();
EventBus bus = getEventBus();
// create needs every trigger execution until 2 needs are created
this.needCreator = new ActionOnEventListener(ctx, new CreateNeedWithFacetsAction(ctx, getBotContextWrapper().getNeedCreateListName()), NO_OF_NEEDS);
bus.subscribe(ActEvent.class, this.needCreator);
// count until 2 needs were created, then
// * connect the 2 needs
this.needConnector = new ActionOnceAfterNEventsListener(ctx, "needConnector", NO_OF_NEEDS, new ConnectFromListToListAction(ctx, ctx.getBotContextWrapper().getNeedCreateListName(), ctx.getBotContextWrapper().getNeedCreateListName(), FacetType.OwnerFacet.getURI(), FacetType.OwnerFacet.getURI(), MILLIS_BETWEEN_MESSAGES, "Hello," + "I am the ConversationBot, a simple bot that will exchange " + "messages and deactivate its needs after some time."));
bus.subscribe(NeedCreatedEvent.class, this.needConnector);
// add a listener that is informed of the connect/open events and that auto-opens
// subscribe it to:
// * connect events - so it responds with open
// * open events - so it responds with open (if the open received was the first open, and we still need to accept the connection)
this.autoOpener = new ActionOnEventListener(ctx, new OpenConnectionAction(ctx, "Hi, I am the ConverssationBot."));
bus.subscribe(ConnectFromOtherNeedEvent.class, this.autoOpener);
// add a listener that auto-responds to messages by a message and at different stages of messages processing fires
// different monitoring events. After specified number of messages, it unsubscribes from all events.
// subscribe it to:
// * message events - so it responds
// * open events - so it initiates the chain reaction of responses
this.autoResponder = new AutomaticMonitoredMessageResponderListener(ctx, NO_OF_MESSAGES, MILLIS_BETWEEN_MESSAGES);
bus.subscribe(OpenFromOtherNeedEvent.class, this.autoResponder);
bus.subscribe(MessageFromOtherNeedEvent.class, this.autoResponder);
// add a listener that closes the connection after it has seen 10 messages
this.connectionCloser = new ActionOnceAfterNEventsListener(ctx, NO_OF_MESSAGES, new CloseConnectionAction(ctx, "Farewell!"));
bus.subscribe(MessageFromOtherNeedEvent.class, this.connectionCloser);
// add a listener that closes the connection when a failureEvent occurs
EventListener onFailureConnectionCloser = new ActionOnEventListener(ctx, new CloseConnectionAction(ctx, "Farewell!"));
bus.subscribe(FailureResponseEvent.class, onFailureConnectionCloser);
// add a listener that auto-responds to a close message with a deactivation of both needs.
// subscribe it to:
// * close events
this.needDeactivator = new ActionOnEventListener(ctx, new DeactivateAllNeedsAction(ctx), 1);
bus.subscribe(CloseFromOtherNeedEvent.class, this.needDeactivator);
// add a listener that counts two NeedDeactivatedEvents and then tells the
// framework that the bot's messaging work is done and connection messages linked data can be crawled
this.crawlReadySignaller = new ActionOnceAfterNEventsListener(ctx, NO_OF_NEEDS, new BaseEventBotAction(ctx) {
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
bus.publish(new CrawlReadyEvent());
}
});
bus.subscribe(NeedDeactivatedEvent.class, this.crawlReadySignaller);
// add a listener that, when crawl is done, tells the
// framework that the bot's work is done
this.workDoneSignaller = new ActionOnEventListener(ctx, new SignalWorkDoneAction(ctx));
bus.subscribe(CrawlDoneEvent.class, this.workDoneSignaller);
// add a listener that reacts to monitoring events
this.monitor = new ActionOnEventListener(ctx, "msgMonitor", new MessageLifecycleMonitoringAction(ctx));
bus.subscribe(MessageDispatchStartedEvent.class, this.monitor);
bus.subscribe(MessageDispatchedEvent.class, this.monitor);
bus.subscribe(SuccessResponseEvent.class, this.monitor);
bus.subscribe(MessageFromOtherNeedEvent.class, this.monitor);
bus.subscribe(CrawlReadyEvent.class, this.monitor);
}
Aggregations