Search in sources :

Example 1 with EventBus

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

the class FactoryHintCheckAction method doRun.

@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
    if (!(event instanceof HintFromMatcherEvent) || !(getEventListenerContext().getBotContextWrapper() instanceof FactoryBotContextWrapper)) {
        logger.error("FactoryHintCheckAction can only handle HintFromMatcherEvent with FactoryBotContextWrapper");
        return;
    }
    FactoryBotContextWrapper botContextWrapper = (FactoryBotContextWrapper) getEventListenerContext().getBotContextWrapper();
    Match match = ((HintFromMatcherEvent) event).getMatch();
    URI ownUri = match.getFromNeed();
    URI requesterUri = match.getToNeed();
    if (botContextWrapper.isFactoryNeed(ownUri)) {
        logger.debug("FactoryHint for factoryURI: " + ownUri + " from the requesterUri: " + requesterUri);
        EventBus bus = getEventListenerContext().getEventBus();
        bus.publish(new FactoryHintEvent(requesterUri, ownUri));
    } else {
        logger.warn("NON FactoryHint for URI: " + ownUri + " from the requesterUri: " + requesterUri + " ignore the hint");
    }
}
Also used : HintFromMatcherEvent(won.bot.framework.eventbot.event.impl.wonmessage.HintFromMatcherEvent) FactoryHintEvent(won.bot.framework.eventbot.event.impl.factory.FactoryHintEvent) EventBus(won.bot.framework.eventbot.bus.EventBus) URI(java.net.URI) FactoryBotContextWrapper(won.bot.framework.bot.context.FactoryBotContextWrapper) Match(won.protocol.model.Match)

Example 2 with EventBus

use of won.bot.framework.eventbot.bus.EventBus 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());
}
Also used : InitializeEvent(won.bot.framework.eventbot.event.impl.lifecycle.InitializeEvent) EventListenerContext(won.bot.framework.eventbot.EventListenerContext) NeedProducerExhaustedEvent(won.bot.framework.eventbot.event.impl.needlifecycle.NeedProducerExhaustedEvent) PublishEventAction(won.bot.framework.eventbot.action.impl.PublishEventAction) EventBus(won.bot.framework.eventbot.bus.EventBus) URI(java.net.URI) CreateNeedCommandEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandEvent) LogMessageCommandFailureAction(won.bot.framework.eventbot.action.impl.wonmessage.execCommand.LogMessageCommandFailureAction) MultipleActions(won.bot.framework.eventbot.action.impl.MultipleActions) ActionOnFirstEventListener(won.bot.framework.eventbot.listener.impl.ActionOnFirstEventListener) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) EventListener(won.bot.framework.eventbot.listener.EventListener) InitFactoryFinishedEvent(won.bot.framework.eventbot.event.impl.factory.InitFactoryFinishedEvent) StartFactoryNeedCreationEvent(won.bot.framework.eventbot.event.impl.factory.StartFactoryNeedCreationEvent) TargetCounterFilter(won.bot.framework.eventbot.filter.impl.TargetCounterFilter) Dataset(org.apache.jena.query.Dataset) Resource(org.apache.jena.rdf.model.Resource) FactoryBotContextWrapper(won.bot.framework.bot.context.FactoryBotContextWrapper) CreateNeedCommandSuccessEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandSuccessEvent) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) MessageCommandEvent(won.bot.framework.eventbot.event.impl.command.MessageCommandEvent) CreateNeedCommandFailureEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandFailureEvent) InitializeEvent(won.bot.framework.eventbot.event.impl.lifecycle.InitializeEvent) FactoryNeedCreationSkippedEvent(won.bot.framework.eventbot.event.impl.factory.FactoryNeedCreationSkippedEvent) MessageCommandResultEvent(won.bot.framework.eventbot.event.impl.command.MessageCommandResultEvent) CreateNeedCommandSuccessEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandSuccessEvent) MessageCommandFailureEvent(won.bot.framework.eventbot.event.impl.command.MessageCommandFailureEvent) InitFactoryFinishedEvent(won.bot.framework.eventbot.event.impl.factory.InitFactoryFinishedEvent) StartFactoryNeedCreationEvent(won.bot.framework.eventbot.event.impl.factory.StartFactoryNeedCreationEvent) Event(won.bot.framework.eventbot.event.Event) NeedProducerExhaustedEvent(won.bot.framework.eventbot.event.impl.needlifecycle.NeedProducerExhaustedEvent) CreateNeedCommandEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandEvent) ExecuteCreateNeedCommandAction(won.bot.framework.eventbot.action.impl.wonmessage.execCommand.ExecuteCreateNeedCommandAction) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) ActionOnFirstEventListener(won.bot.framework.eventbot.listener.impl.ActionOnFirstEventListener) FactoryNeedCreationSkippedEvent(won.bot.framework.eventbot.event.impl.factory.FactoryNeedCreationSkippedEvent) NeedProducer(won.bot.framework.component.needproducer.NeedProducer)

Example 3 with EventBus

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

the class MailCommandAction method processNonReferenceMailCommand.

private void processNonReferenceMailCommand(MimeMessage message) throws IOException, MessagingException {
    EventBus bus = getEventListenerContext().getEventBus();
    ActionType mailAction = mailContentExtractor.getMailAction(message);
    switch(mailAction) {
        case SUBSCRIBE:
            bus.publish(new SubscribeUnsubscribeEvent(message, SubscribeStatus.SUBSCRIBED));
            break;
        case UNSUBSCRIBE:
            bus.publish(new SubscribeUnsubscribeEvent(message, SubscribeStatus.UNSUBSCRIBED));
            break;
        case CLOSE_NEED:
            /*A need can be closed with a mail that matches the takenCmdPattern in its subject and has the same title
                 as a previously created need by the user*/
            URI needUri = retrieveCorrespondingNeedUriFromMailByTitle(message);
            if (needUri != null) {
                bus.publish(new DeactivateNeedCommandEvent(needUri));
            }
            break;
        case NO_ACTION:
        default:
            // INVALID COMMAND
            logger.error("No command was given or assumed");
            break;
    }
}
Also used : ActionType(won.bot.framework.eventbot.action.impl.mail.model.ActionType) SubscribeUnsubscribeEvent(won.bot.framework.eventbot.event.impl.mail.SubscribeUnsubscribeEvent) DeactivateNeedCommandEvent(won.bot.framework.eventbot.event.impl.command.deactivate.DeactivateNeedCommandEvent) EventBus(won.bot.framework.eventbot.bus.EventBus) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) URI(java.net.URI)

Example 4 with EventBus

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

the class MailParserAction method processCreateNeedMail.

private void processCreateNeedMail(MimeMessage message) throws MessagingException, IOException {
    EventListenerContext ctx = getEventListenerContext();
    EventBus bus = ctx.getEventBus();
    String senderMailAddress = MailContentExtractor.getMailSender(message);
    MailBotContextWrapper botContextWrapper = ((MailBotContextWrapper) ctx.getBotContextWrapper());
    SubscribeStatus subscribeStatus = botContextWrapper.getSubscribeStatusForMailAddress(senderMailAddress);
    // published as needs, discarded or cached
    if (SubscribeStatus.SUBSCRIBED.equals(subscribeStatus)) {
        logger.info("received a create mail from subscribed user '{}' with subject '{}' so publish as need", senderMailAddress, message.getSubject());
        bus.publish(new CreateNeedFromMailEvent(message));
    } else if (SubscribeStatus.UNSUBSCRIBED.equals(subscribeStatus)) {
        logger.info("received mail from unsubscribed user '{}' so discard mail with subject '{}'", senderMailAddress, message.getSubject());
    } else {
        logger.info("received a create mail from new user '{}' with subject '{}' so cache it and send welcome mail", senderMailAddress, message.getSubject());
        botContextWrapper.addCachedMailsForMailAddress(message);
        bus.publish(new WelcomeMailEvent(message));
    }
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) SubscribeStatus(won.bot.framework.eventbot.action.impl.mail.model.SubscribeStatus) MailBotContextWrapper(won.bot.framework.bot.context.MailBotContextWrapper) WelcomeMailEvent(won.bot.framework.eventbot.event.impl.mail.WelcomeMailEvent) EventBus(won.bot.framework.eventbot.bus.EventBus) CreateNeedFromMailEvent(won.bot.framework.eventbot.event.impl.mail.CreateNeedFromMailEvent)

Example 5 with EventBus

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

the class SubscribeUnsubscribeAction method doRun.

@Override
protected void doRun(final Event event, EventListener executingListener) throws Exception {
    EventListenerContext ctx = getEventListenerContext();
    if (event instanceof SubscribeUnsubscribeEvent && ctx.getBotContextWrapper() instanceof MailBotContextWrapper) {
        MailBotContextWrapper botContextWrapper = (MailBotContextWrapper) ctx.getBotContextWrapper();
        // save the new subscription status of the user to the bot context
        SubscribeUnsubscribeEvent subscribeEvent = (SubscribeUnsubscribeEvent) event;
        SubscribeStatus subscribeStatus = subscribeEvent.getSubscribeStatus();
        String senderMailAddress = MailContentExtractor.getMailSender(subscribeEvent.getMessage());
        botContextWrapper.setSubscribeStatusForMailAddress(senderMailAddress, subscribeStatus);
        // depending on the new subscribe status of the user publish his cached mails as needs or delete the cache
        if (SubscribeStatus.SUBSCRIBED.equals(subscribeStatus)) {
            EventBus bus = getEventListenerContext().getEventBus();
            Collection<MimeMessage> cachedMessages = botContextWrapper.loadCachedMailsForMailAddress(senderMailAddress);
            cachedMessages.stream().forEach(message -> bus.publish(new CreateNeedFromMailEvent(message)));
        } else if (SubscribeStatus.UNSUBSCRIBED.equals(subscribeStatus)) {
            botContextWrapper.removeCachedMailsForMailAddress(senderMailAddress);
        }
    }
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) SubscribeStatus(won.bot.framework.eventbot.action.impl.mail.model.SubscribeStatus) MailBotContextWrapper(won.bot.framework.bot.context.MailBotContextWrapper) MimeMessage(javax.mail.internet.MimeMessage) SubscribeUnsubscribeEvent(won.bot.framework.eventbot.event.impl.mail.SubscribeUnsubscribeEvent) EventBus(won.bot.framework.eventbot.bus.EventBus) CreateNeedFromMailEvent(won.bot.framework.eventbot.event.impl.mail.CreateNeedFromMailEvent)

Aggregations

EventBus (won.bot.framework.eventbot.bus.EventBus)31 EventListenerContext (won.bot.framework.eventbot.EventListenerContext)28 EventListener (won.bot.framework.eventbot.listener.EventListener)19 ActionOnEventListener (won.bot.framework.eventbot.listener.impl.ActionOnEventListener)19 Event (won.bot.framework.eventbot.event.Event)18 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 URI (java.net.URI)12 ActEvent (won.bot.framework.eventbot.event.impl.lifecycle.ActEvent)11 BaseEventListener (won.bot.framework.eventbot.listener.BaseEventListener)11 ConnectFromListToListAction (won.bot.framework.eventbot.action.impl.wonmessage.ConnectFromListToListAction)10 NeedCreatedEvent (won.bot.framework.eventbot.event.impl.needlifecycle.NeedCreatedEvent)10 OpenConnectionAction (won.bot.framework.eventbot.action.impl.wonmessage.OpenConnectionAction)8 DeactivateAllNeedsAction (won.bot.framework.eventbot.action.impl.needlifecycle.DeactivateAllNeedsAction)6 Dataset (org.apache.jena.query.Dataset)5 DeactivateAllNeedsOfListAction (won.bot.framework.eventbot.action.impl.needlifecycle.DeactivateAllNeedsOfListAction)5 CloseConnectionAction (won.bot.framework.eventbot.action.impl.wonmessage.CloseConnectionAction)5 FinishedEventFilter (won.bot.framework.eventbot.filter.impl.FinishedEventFilter)5