Search in sources :

Example 1 with CreateNeedCommandSuccessEvent

use of won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandSuccessEvent 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 2 with CreateNeedCommandSuccessEvent

use of won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandSuccessEvent in project webofneeds by researchstudio-sat.

the class ExecuteCreateNeedCommandAction method doRun.

@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
    if (!(event instanceof CreateNeedCommandEvent))
        return;
    CreateNeedCommandEvent createNeedCommandEvent = (CreateNeedCommandEvent) event;
    Dataset needDataset = createNeedCommandEvent.getNeedDataset();
    List<URI> facets = createNeedCommandEvent.getFacets();
    if (needDataset == null) {
        logger.warn("CreateNeedCommandEvent did not contain a need model, aborting need creation");
        getEventListenerContext().getEventBus().publish(new NeedCreationAbortedEvent(null, null, createNeedCommandEvent, "CreateNeedCommandEvent did not contain a need model, aborting need creation"));
        return;
    }
    URI needUriFromProducer = null;
    Resource needResource = WonRdfUtils.NeedUtils.getNeedResource(needDataset);
    if (needResource.isURIResource()) {
        needUriFromProducer = URI.create(needResource.getURI().toString());
        RdfUtils.replaceBaseURI(needDataset, needResource.getURI());
    } else {
        RdfUtils.replaceBaseResource(needDataset, needResource);
    }
    final URI needUriBeforeCreation = needUriFromProducer;
    NeedModelWrapper needModelWrapper = new NeedModelWrapper(needDataset);
    for (URI facetURI : facets) {
        WonRdfUtils.FacetUtils.addFacet(needModelWrapper.getNeedModel(), facetURI);
    }
    final Dataset needDatasetWithFacets = needModelWrapper.copyDataset();
    final URI wonNodeUri = getEventListenerContext().getNodeURISource().getNodeURI();
    logger.debug("creating need on won node {} with content {} ", wonNodeUri, StringUtils.abbreviate(RdfUtils.toString(needDatasetWithFacets), 150));
    WonNodeInformationService wonNodeInformationService = getEventListenerContext().getWonNodeInformationService();
    final URI needURI = wonNodeInformationService.generateNeedURI(wonNodeUri);
    WonMessage createNeedMessage = createWonMessage(wonNodeInformationService, needURI, wonNodeUri, needDatasetWithFacets, createNeedCommandEvent.isUsedForTesting(), createNeedCommandEvent.isDoNotMatch());
    // remember the need URI so we can react to success/failure responses
    EventBotActionUtils.rememberInList(getEventListenerContext(), needURI, createNeedCommandEvent.getUriListName());
    EventListener successCallback = new EventListener() {

        @Override
        public void onEvent(Event event) throws Exception {
            logger.debug("need creation successful, new need URI is {}", needURI);
            getEventListenerContext().getEventBus().publish(new CreateNeedCommandSuccessEvent(needURI, needUriBeforeCreation, createNeedCommandEvent));
        }
    };
    EventListener failureCallback = new EventListener() {

        @Override
        public void onEvent(Event event) throws Exception {
            String textMessage = WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) event).getFailureMessage());
            logger.debug("need creation failed for need URI {}, original message URI {}: {}", new Object[] { needURI, ((FailureResponseEvent) event).getOriginalMessageURI(), textMessage });
            getEventListenerContext().getEventBus().publish(new CreateNeedCommandFailureEvent(needURI, needUriBeforeCreation, createNeedCommandEvent, textMessage));
            EventBotActionUtils.removeFromList(getEventListenerContext(), needURI, createNeedCommandEvent.getUriListName());
        }
    };
    EventBotActionUtils.makeAndSubscribeResponseListener(createNeedMessage, successCallback, failureCallback, getEventListenerContext());
    logger.debug("registered listeners for response to message URI {}", createNeedMessage.getMessageURI());
    getEventListenerContext().getWonMessageSender().sendWonMessage(createNeedMessage);
    logger.debug("need creation message sent with message URI {}", createNeedMessage.getMessageURI());
}
Also used : NeedCreationAbortedEvent(won.bot.framework.eventbot.event.impl.command.create.NeedCreationAbortedEvent) Dataset(org.apache.jena.query.Dataset) CreateNeedCommandFailureEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandFailureEvent) Resource(org.apache.jena.rdf.model.Resource) WonNodeInformationService(won.protocol.service.WonNodeInformationService) NeedModelWrapper(won.protocol.util.NeedModelWrapper) URI(java.net.URI) CreateNeedCommandEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandEvent) WonMessage(won.protocol.message.WonMessage) CreateNeedCommandSuccessEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandSuccessEvent) CreateNeedCommandFailureEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandFailureEvent) CreateNeedCommandSuccessEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandSuccessEvent) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) Event(won.bot.framework.eventbot.event.Event) CreateNeedCommandEvent(won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandEvent) NeedCreationAbortedEvent(won.bot.framework.eventbot.event.impl.command.create.NeedCreationAbortedEvent) EventListener(won.bot.framework.eventbot.listener.EventListener)

Aggregations

URI (java.net.URI)2 Dataset (org.apache.jena.query.Dataset)2 Resource (org.apache.jena.rdf.model.Resource)2 Event (won.bot.framework.eventbot.event.Event)2 CreateNeedCommandEvent (won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandEvent)2 CreateNeedCommandFailureEvent (won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandFailureEvent)2 CreateNeedCommandSuccessEvent (won.bot.framework.eventbot.event.impl.command.create.CreateNeedCommandSuccessEvent)2 EventListener (won.bot.framework.eventbot.listener.EventListener)2 FactoryBotContextWrapper (won.bot.framework.bot.context.FactoryBotContextWrapper)1 NeedProducer (won.bot.framework.component.needproducer.NeedProducer)1 EventListenerContext (won.bot.framework.eventbot.EventListenerContext)1 BaseEventBotAction (won.bot.framework.eventbot.action.BaseEventBotAction)1 MultipleActions (won.bot.framework.eventbot.action.impl.MultipleActions)1 PublishEventAction (won.bot.framework.eventbot.action.impl.PublishEventAction)1 ExecuteCreateNeedCommandAction (won.bot.framework.eventbot.action.impl.wonmessage.execCommand.ExecuteCreateNeedCommandAction)1 LogMessageCommandFailureAction (won.bot.framework.eventbot.action.impl.wonmessage.execCommand.LogMessageCommandFailureAction)1 EventBus (won.bot.framework.eventbot.bus.EventBus)1 MessageCommandEvent (won.bot.framework.eventbot.event.impl.command.MessageCommandEvent)1 MessageCommandFailureEvent (won.bot.framework.eventbot.event.impl.command.MessageCommandFailureEvent)1 MessageCommandResultEvent (won.bot.framework.eventbot.event.impl.command.MessageCommandResultEvent)1