Search in sources :

Example 11 with EventListenerContext

use of won.bot.framework.eventbot.EventListenerContext in project webofneeds by researchstudio-sat.

the class Message2MailAction method doRun.

@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
    EventListenerContext ctx = getEventListenerContext();
    if (event instanceof MessageFromOtherNeedEvent && ctx.getBotContextWrapper() instanceof MailBotContextWrapper) {
        MailBotContextWrapper botContextWrapper = (MailBotContextWrapper) ctx.getBotContextWrapper();
        Connection con = ((MessageFromOtherNeedEvent) event).getCon();
        URI responseTo = con.getNeedURI();
        URI remoteNeedUri = con.getRemoteNeedURI();
        MimeMessage originalMail = botContextWrapper.getMimeMessageForURI(responseTo);
        logger.debug("Someone sent a message for URI: " + responseTo + " sending a mail to the creator: " + MailContentExtractor.getFromAddressString(originalMail));
        WonMimeMessage answerMessage = mailGenerator.createMessageMail(originalMail, responseTo, remoteNeedUri, con.getConnectionURI());
        botContextWrapper.addMailIdWonURIRelation(answerMessage.getMessageID(), new WonURI(con.getConnectionURI(), UriType.CONNECTION));
        sendChannel.send(new GenericMessage<>(answerMessage));
    } else {
        logger.debug("event was not of type MessageFromOtherNeedEvent");
    }
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) MessageFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.MessageFromOtherNeedEvent) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) MailBotContextWrapper(won.bot.framework.bot.context.MailBotContextWrapper) MimeMessage(javax.mail.internet.MimeMessage) Connection(won.protocol.model.Connection) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) URI(java.net.URI)

Example 12 with EventListenerContext

use of won.bot.framework.eventbot.EventListenerContext in project webofneeds by researchstudio-sat.

the class CrawlAction method doRun.

@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
    if (!(event instanceof CrawlCommandEvent))
        return;
    CrawlCommandEvent crawlCommandEvent = (CrawlCommandEvent) event;
    EventListenerContext ctx = getEventListenerContext();
    logger.debug("starting crawl for {}", crawlCommandEvent.getStartURI());
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Dataset crawledData = null;
    try {
        crawledData = ctx.getLinkedDataSource().getDataForResourceWithPropertyPath(crawlCommandEvent.getStartURI(), crawlCommandEvent.getNeedURI(), crawlCommandEvent.getPropertyPaths(), crawlCommandEvent.getGetMaxRequest(), crawlCommandEvent.getMaxDepth());
    } catch (Exception e) {
        logger.debug("caught exeption during crawl for {}", crawlCommandEvent.getStartURI(), e);
        ctx.getEventBus().publish(new CrawlCommandFailureEvent(crawlCommandEvent, "Could not crawl " + crawlCommandEvent.getStartURI() + " with WebID " + crawlCommandEvent.getNeedURI() + ": caught " + e));
        return;
    }
    stopWatch.stop();
    logger.debug("finished crawl for {} in {} millis", crawlCommandEvent.getStartURI(), stopWatch.getTotalTimeMillis());
    ctx.getEventBus().publish(new CrawlCommandSuccessEvent(crawlCommandEvent, crawledData, "Finished crawling " + crawlCommandEvent.getStartURI() + " in " + stopWatch.getTotalTimeMillis()));
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) CrawlCommandEvent(won.bot.framework.eventbot.event.impl.crawl.CrawlCommandEvent) CrawlCommandFailureEvent(won.bot.framework.eventbot.event.impl.crawl.CrawlCommandFailureEvent) Dataset(org.apache.jena.query.Dataset) CrawlCommandSuccessEvent(won.bot.framework.eventbot.event.impl.crawl.CrawlCommandSuccessEvent) StopWatch(org.springframework.util.StopWatch)

Example 13 with EventListenerContext

use of won.bot.framework.eventbot.EventListenerContext 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);
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) ActionOnceAfterNEventsListener(won.bot.framework.eventbot.listener.impl.ActionOnceAfterNEventsListener) AdditionalParticipantCoordinatorBotContextWrapper(won.bot.framework.bot.context.AdditionalParticipantCoordinatorBotContextWrapper) BaseEventListener(won.bot.framework.eventbot.listener.BaseEventListener) EventBus(won.bot.framework.eventbot.bus.EventBus) URI(java.net.URI) DeactivateAllNeedsOfListAction(won.bot.framework.eventbot.action.impl.needlifecycle.DeactivateAllNeedsOfListAction) ConnectFromListToListAction(won.bot.framework.eventbot.action.impl.wonmessage.ConnectFromListToListAction) BaseEventListener(won.bot.framework.eventbot.listener.BaseEventListener) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) EventListener(won.bot.framework.eventbot.listener.EventListener) WaitForNEventsListener(won.bot.framework.eventbot.listener.impl.WaitForNEventsListener) BATestBotScript(won.bot.framework.eventbot.listener.baStateBots.BATestBotScript) CreateNeedWithFacetsAction(won.bot.framework.eventbot.action.impl.needlifecycle.CreateNeedWithFacetsAction) OrFilter(won.bot.framework.eventbot.filter.impl.OrFilter) SignalWorkDoneAction(won.bot.framework.eventbot.action.impl.lifecycle.SignalWorkDoneAction) SecondPhaseStartedEvent(won.bot.framework.eventbot.listener.baStateBots.baCCMessagingBots.atomicBots.SecondPhaseStartedEvent) BATestScriptListener(won.bot.framework.eventbot.listener.baStateBots.BATestScriptListener) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) MessageFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.MessageFromOtherNeedEvent) SecondPhaseStartedEvent(won.bot.framework.eventbot.listener.baStateBots.baCCMessagingBots.atomicBots.SecondPhaseStartedEvent) NeedCreatedEvent(won.bot.framework.eventbot.event.impl.needlifecycle.NeedCreatedEvent) FinishedEvent(won.bot.framework.eventbot.event.impl.listener.FinishedEvent) ConnectFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherNeedEvent) OpenFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.OpenFromOtherNeedEvent) Event(won.bot.framework.eventbot.event.Event) ActEvent(won.bot.framework.eventbot.event.impl.lifecycle.ActEvent) CloseFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.CloseFromOtherNeedEvent) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) AcceptOnceFilter(won.bot.framework.eventbot.filter.impl.AcceptOnceFilter) FinishedEventFilter(won.bot.framework.eventbot.filter.impl.FinishedEventFilter)

Example 14 with EventListenerContext

use of won.bot.framework.eventbot.EventListenerContext 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);
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) ActionOnceAfterNEventsListener(won.bot.framework.eventbot.listener.impl.ActionOnceAfterNEventsListener) CloseConnectionAction(won.bot.framework.eventbot.action.impl.wonmessage.CloseConnectionAction) CreateNeedWithFacetsAction(won.bot.framework.eventbot.action.impl.needlifecycle.CreateNeedWithFacetsAction) EventBus(won.bot.framework.eventbot.bus.EventBus) OpenConnectionAction(won.bot.framework.eventbot.action.impl.wonmessage.OpenConnectionAction) SignalWorkDoneAction(won.bot.framework.eventbot.action.impl.lifecycle.SignalWorkDoneAction) MessageLifecycleMonitoringAction(won.bot.framework.eventbot.action.impl.monitor.MessageLifecycleMonitoringAction) CrawlReadyEvent(won.bot.framework.eventbot.event.impl.monitor.CrawlReadyEvent) DeactivateAllNeedsAction(won.bot.framework.eventbot.action.impl.needlifecycle.DeactivateAllNeedsAction) ConnectFromListToListAction(won.bot.framework.eventbot.action.impl.wonmessage.ConnectFromListToListAction) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) NeedDeactivatedEvent(won.bot.framework.eventbot.event.impl.needlifecycle.NeedDeactivatedEvent) MessageDispatchedEvent(won.bot.framework.eventbot.event.impl.monitor.MessageDispatchedEvent) CrawlReadyEvent(won.bot.framework.eventbot.event.impl.monitor.CrawlReadyEvent) NeedCreatedEvent(won.bot.framework.eventbot.event.impl.needlifecycle.NeedCreatedEvent) CrawlDoneEvent(won.bot.framework.eventbot.event.impl.monitor.CrawlDoneEvent) Event(won.bot.framework.eventbot.event.Event) ActEvent(won.bot.framework.eventbot.event.impl.lifecycle.ActEvent) MessageDispatchStartedEvent(won.bot.framework.eventbot.event.impl.monitor.MessageDispatchStartedEvent) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) BaseEventListener(won.bot.framework.eventbot.listener.BaseEventListener) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) EventListener(won.bot.framework.eventbot.listener.EventListener) AutomaticMonitoredMessageResponderListener(won.bot.framework.eventbot.listener.impl.AutomaticMonitoredMessageResponderListener)

Example 15 with EventListenerContext

use of won.bot.framework.eventbot.EventListenerContext in project webofneeds by researchstudio-sat.

the class DebugBot method initializeEventListeners.

@Override
protected void initializeEventListeners() {
    String welcomeMessage = "Greetings! \nI am the DebugBot. I " + "can simulate multiple other users so you can test things. I understand a few commands. \nTo see which ones, " + "type 'usage'.";
    String welcomeHelpMessage = "When connecting with me, you can say 'ignore', or 'deny' to make me ignore or deny requests, and 'wait N' to make me wait N seconds (max 99) before reacting.";
    EventListenerContext ctx = getEventListenerContext();
    EventBus bus = getEventBus();
    // eagerly cache RDF data
    BotBehaviour eagerlyCacheBehaviour = new EagerlyPopulateCacheBehaviour(ctx);
    eagerlyCacheBehaviour.activate();
    // react to a bot command activating/deactivating eager caching
    bus.subscribe(SetCacheEagernessCommandEvent.class, new ActionOnEventListener(ctx, new BaseEventBotAction(ctx) {

        @Override
        protected void doRun(Event event, EventListener executingListener) throws Exception {
            if (event instanceof SetCacheEagernessCommandEvent) {
                if (((SetCacheEagernessCommandEvent) event).isEager()) {
                    eagerlyCacheBehaviour.activate();
                } else {
                    eagerlyCacheBehaviour.deactivate();
                }
            }
        }
    }));
    // react to a message that was not identified as a debug command
    BotBehaviour connectionMessageBehaviour = new ConnectionMessageBehaviour(ctx);
    connectionMessageBehaviour.activate();
    // react to the debug deactivate command (deactivate my need)
    BotBehaviour deactivateNeedBehaviour = new DeactivateNeedBehaviour(ctx);
    deactivateNeedBehaviour.activate();
    // react to the close behaviour
    BotBehaviour closeBehaviour = new CloseBevahiour(ctx);
    closeBehaviour.activate();
    // register with WoN nodes, be notified when new needs are created
    RegisterMatcherAction registerMatcherAction = new RegisterMatcherAction(ctx);
    this.matcherRegistrator = new ActionOnEventListener(ctx, registerMatcherAction, 1);
    bus.subscribe(ActEvent.class, this.matcherRegistrator);
    RandomDelayedAction delayedRegistration = new RandomDelayedAction(ctx, registrationMatcherRetryInterval, registrationMatcherRetryInterval, 0, registerMatcherAction);
    ActionOnEventListener matcherRetryRegistrator = new ActionOnEventListener(ctx, delayedRegistration);
    bus.subscribe(MatcherRegisterFailedEvent.class, matcherRetryRegistrator);
    // create the echo need for debug initial connect - if we're not reacting to the creation of our own echo need.
    CreateDebugNeedWithFacetsAction needForInitialConnectAction = new CreateDebugNeedWithFacetsAction(ctx, true, true);
    needForInitialConnectAction.setIsInitialForConnect(true);
    ActionOnEventListener initialConnector = new ActionOnEventListener(ctx, new NotFilter(new NeedUriInNamedListFilter(ctx, ctx.getBotContextWrapper().getNeedCreateListName())), needForInitialConnectAction);
    bus.subscribe(NeedCreatedEventForMatcher.class, initialConnector);
    // create the echo need for debug initial hint - if we're not reacting to the creation of our own echo need.
    CreateDebugNeedWithFacetsAction initialHinter = new CreateDebugNeedWithFacetsAction(ctx, true, true);
    initialHinter.setIsInitialForHint(true);
    ActionOnEventListener needForInitialHintListener = new ActionOnEventListener(ctx, new NotFilter(new NeedUriInNamedListFilter(ctx, ctx.getBotContextWrapper().getNeedCreateListName())), initialHinter);
    bus.subscribe(NeedCreatedEventForMatcher.class, needForInitialHintListener);
    // as soon as the echo need triggered by debug connect created, connect to original
    this.needConnector = new ActionOnEventListener(ctx, "needConnector", new RandomDelayedAction(ctx, CONNECT_DELAY_MILLIS, CONNECT_DELAY_MILLIS, 1, new ConnectWithAssociatedNeedAction(ctx, FacetType.OwnerFacet.getURI(), FacetType.OwnerFacet.getURI(), welcomeMessage + " " + welcomeHelpMessage)));
    bus.subscribe(NeedCreatedEventForDebugConnect.class, this.needConnector);
    // as soon as the echo need triggered by debug hint command created, hint to original
    this.needHinter = new ActionOnEventListener(ctx, "needHinter", new RandomDelayedAction(ctx, CONNECT_DELAY_MILLIS, CONNECT_DELAY_MILLIS, 1, new HintAssociatedNeedAction(ctx, FacetType.OwnerFacet.getURI(), FacetType.OwnerFacet.getURI(), matcherUri)));
    bus.subscribe(NeedCreatedEventForDebugHint.class, this.needHinter);
    // if the original need wants to connect - always open
    this.autoOpener = new ActionOnEventListener(ctx, new MultipleActions(ctx, new OpenConnectionDebugAction(ctx, welcomeMessage, welcomeHelpMessage), new PublishSetChattinessEventAction(ctx, true)));
    bus.subscribe(ConnectFromOtherNeedEvent.class, this.autoOpener);
    EventBotAction userCommandAction = new DebugBotIncomingMessageToEventMappingAction(ctx);
    // if the remote side opens, send a greeting and set to chatty.
    bus.subscribe(OpenFromOtherNeedEvent.class, new ActionOnEventListener(ctx, new MultipleActions(ctx, userCommandAction, new PublishSetChattinessEventAction(ctx, true))));
    // if the bot receives a text message - try to map the command of the text message to a DebugEvent
    messageFromOtherNeedListener = new ActionOnEventListener(ctx, userCommandAction);
    bus.subscribe(MessageFromOtherNeedEvent.class, messageFromOtherNeedListener);
    // react to usage command event
    this.usageMessageSender = new ActionOnEventListener(ctx, new SendMultipleMessagesAction(ctx, DebugBotIncomingMessageToEventMappingAction.USAGE_MESSAGES));
    bus.subscribe(UsageDebugCommandEvent.class, usageMessageSender);
    bus.subscribe(CloseCommandSuccessEvent.class, new ActionOnEventListener(ctx, "chattiness off", new PublishSetChattinessEventAction(ctx, false)));
    // react to close event: set connection to not chatty
    bus.subscribe(CloseFromOtherNeedEvent.class, new ActionOnEventListener(ctx, new PublishSetChattinessEventAction(ctx, false)));
    // react to the hint and connect commands by creating a need (it will fire correct need created for connect/hint
    // events)
    needCreator = new ActionOnEventListener(ctx, new CreateDebugNeedWithFacetsAction(ctx, true, true));
    bus.subscribe(HintDebugCommandEvent.class, needCreator);
    bus.subscribe(ConnectDebugCommandEvent.class, needCreator);
    bus.subscribe(SendNDebugCommandEvent.class, new ActionOnEventListener(ctx, new SendNDebugMessagesAction(ctx, DELAY_BETWEEN_N_MESSAGES, DebugBotIncomingMessageToEventMappingAction.N_MESSAGES)));
    MessageTimingManager timingManager = new MessageTimingManager(ctx, 20);
    // on every actEvent there is a chance we send a chatty message
    bus.subscribe(ActEvent.class, new ActionOnEventListener(ctx, new SendChattyMessageAction(ctx, CHATTY_MESSAGE_PROBABILITY, timingManager, DebugBotIncomingMessageToEventMappingAction.RANDOM_MESSAGES, DebugBotIncomingMessageToEventMappingAction.LAST_MESSAGES)));
    // set the chattiness of the connection
    bus.subscribe(SetChattinessDebugCommandEvent.class, new ActionOnEventListener(ctx, new SetChattinessAction(ctx)));
    // process eliza messages with eliza
    bus.subscribe(MessageToElizaEvent.class, new ActionOnEventListener(ctx, new AnswerWithElizaAction(ctx, 20)));
    // remember when we sent the last message
    bus.subscribe(WonMessageSentOnConnectionEvent.class, new ActionOnEventListener(ctx, new RecordMessageSentTimeAction(ctx, timingManager)));
    // remember when we got the last message
    bus.subscribe(WonMessageReceivedOnConnectionEvent.class, new ActionOnEventListener(ctx, new RecordMessageReceivedTimeAction(ctx, timingManager)));
    // initialize the sent timestamp when the open message is received
    bus.subscribe(OpenFromOtherNeedEvent.class, new ActionOnEventListener(ctx, new RecordMessageSentTimeAction(ctx, timingManager)));
    // initialize the sent timestamp when the connect message is received
    bus.subscribe(ConnectFromOtherNeedEvent.class, new ActionOnEventListener(ctx, new RecordMessageSentTimeAction(ctx, timingManager)));
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) CreateDebugNeedWithFacetsAction(won.bot.framework.eventbot.action.impl.debugbot.CreateDebugNeedWithFacetsAction) SendMultipleMessagesAction(won.bot.framework.eventbot.action.impl.wonmessage.SendMultipleMessagesAction) NeedUriInNamedListFilter(won.bot.framework.eventbot.filter.impl.NeedUriInNamedListFilter) SendNDebugMessagesAction(won.bot.framework.eventbot.action.impl.debugbot.SendNDebugMessagesAction) EventBus(won.bot.framework.eventbot.bus.EventBus) HintAssociatedNeedAction(won.bot.framework.eventbot.action.impl.wonmessage.HintAssociatedNeedAction) MultipleActions(won.bot.framework.eventbot.action.impl.MultipleActions) PublishSetChattinessEventAction(won.bot.framework.eventbot.action.impl.debugbot.PublishSetChattinessEventAction) DebugBotIncomingMessageToEventMappingAction(won.bot.framework.eventbot.action.impl.debugbot.DebugBotIncomingMessageToEventMappingAction) OpenConnectionDebugAction(won.bot.framework.eventbot.action.impl.debugbot.OpenConnectionDebugAction) BaseEventListener(won.bot.framework.eventbot.listener.BaseEventListener) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) EventListener(won.bot.framework.eventbot.listener.EventListener) RandomDelayedAction(won.bot.framework.eventbot.action.impl.RandomDelayedAction) CloseBevahiour(won.bot.framework.eventbot.behaviour.CloseBevahiour) ConnectWithAssociatedNeedAction(won.bot.framework.eventbot.action.impl.wonmessage.ConnectWithAssociatedNeedAction) BotBehaviour(won.bot.framework.eventbot.behaviour.BotBehaviour) RecordMessageSentTimeAction(won.bot.framework.eventbot.action.impl.debugbot.RecordMessageSentTimeAction) SetChattinessAction(won.bot.framework.eventbot.action.impl.debugbot.SetChattinessAction) AnswerWithElizaAction(won.bot.framework.eventbot.action.impl.debugbot.AnswerWithElizaAction) EagerlyPopulateCacheBehaviour(won.bot.framework.eventbot.behaviour.EagerlyPopulateCacheBehaviour) RecordMessageReceivedTimeAction(won.bot.framework.eventbot.action.impl.debugbot.RecordMessageReceivedTimeAction) SetCacheEagernessCommandEvent(won.bot.framework.eventbot.event.impl.debugbot.SetCacheEagernessCommandEvent) RegisterMatcherAction(won.bot.framework.eventbot.action.impl.matcher.RegisterMatcherAction) ConnectionMessageBehaviour(won.bot.framework.eventbot.behaviour.ConnectionMessageBehaviour) NotFilter(won.bot.framework.eventbot.filter.impl.NotFilter) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) UsageDebugCommandEvent(won.bot.framework.eventbot.event.impl.debugbot.UsageDebugCommandEvent) MatcherRegisterFailedEvent(won.bot.framework.eventbot.event.impl.matcher.MatcherRegisterFailedEvent) HintDebugCommandEvent(won.bot.framework.eventbot.event.impl.debugbot.HintDebugCommandEvent) OpenFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.OpenFromOtherNeedEvent) Event(won.bot.framework.eventbot.event.Event) SendNDebugCommandEvent(won.bot.framework.eventbot.event.impl.debugbot.SendNDebugCommandEvent) CloseFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.CloseFromOtherNeedEvent) MessageFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.MessageFromOtherNeedEvent) CloseCommandSuccessEvent(won.bot.framework.eventbot.event.impl.command.close.CloseCommandSuccessEvent) SetChattinessDebugCommandEvent(won.bot.framework.eventbot.event.impl.debugbot.SetChattinessDebugCommandEvent) WonMessageReceivedOnConnectionEvent(won.bot.framework.eventbot.event.impl.wonmessage.WonMessageReceivedOnConnectionEvent) ConnectDebugCommandEvent(won.bot.framework.eventbot.event.impl.debugbot.ConnectDebugCommandEvent) MessageToElizaEvent(won.bot.framework.eventbot.event.impl.debugbot.MessageToElizaEvent) ConnectFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherNeedEvent) WonMessageSentOnConnectionEvent(won.bot.framework.eventbot.event.impl.wonmessage.WonMessageSentOnConnectionEvent) ActEvent(won.bot.framework.eventbot.event.impl.lifecycle.ActEvent) SetCacheEagernessCommandEvent(won.bot.framework.eventbot.event.impl.debugbot.SetCacheEagernessCommandEvent) DeactivateNeedBehaviour(won.bot.framework.eventbot.behaviour.DeactivateNeedBehaviour) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) MessageTimingManager(won.bot.framework.eventbot.action.impl.debugbot.MessageTimingManager) SendChattyMessageAction(won.bot.framework.eventbot.action.impl.debugbot.SendChattyMessageAction) EventBotAction(won.bot.framework.eventbot.action.EventBotAction) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction)

Aggregations

EventListenerContext (won.bot.framework.eventbot.EventListenerContext)44 EventBus (won.bot.framework.eventbot.bus.EventBus)26 ActionOnEventListener (won.bot.framework.eventbot.listener.impl.ActionOnEventListener)23 EventListener (won.bot.framework.eventbot.listener.EventListener)22 Event (won.bot.framework.eventbot.event.Event)21 URI (java.net.URI)20 BaseEventBotAction (won.bot.framework.eventbot.action.BaseEventBotAction)16 CreateNeedWithFacetsAction (won.bot.framework.eventbot.action.impl.needlifecycle.CreateNeedWithFacetsAction)15 SignalWorkDoneAction (won.bot.framework.eventbot.action.impl.lifecycle.SignalWorkDoneAction)14 ActionOnceAfterNEventsListener (won.bot.framework.eventbot.listener.impl.ActionOnceAfterNEventsListener)14 NeedCreatedEvent (won.bot.framework.eventbot.event.impl.needlifecycle.NeedCreatedEvent)12 ActEvent (won.bot.framework.eventbot.event.impl.lifecycle.ActEvent)11 BaseEventListener (won.bot.framework.eventbot.listener.BaseEventListener)11 WonMessage (won.protocol.message.WonMessage)11 WonURI (won.bot.framework.eventbot.action.impl.mail.model.WonURI)10 ConnectFromListToListAction (won.bot.framework.eventbot.action.impl.wonmessage.ConnectFromListToListAction)10 Dataset (org.apache.jena.query.Dataset)9 OpenConnectionAction (won.bot.framework.eventbot.action.impl.wonmessage.OpenConnectionAction)8 ConnectFromOtherNeedEvent (won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherNeedEvent)7 Connection (won.protocol.model.Connection)7