use of won.bot.framework.eventbot.EventListenerContext in project webofneeds by researchstudio-sat.
the class FactoryBot method initializeEventListeners.
@Override
protected final void initializeEventListeners() {
if (!(super.getBotContextWrapper() instanceof FactoryBotContextWrapper)) {
logger.error("FactoryBot does not work without a FactoryBotContextWrapper");
throw new IllegalStateException("FactoryBot does not work without a FactoryBotContextWrapper");
}
if (getNeedProducer() == null) {
logger.error("FactoryBots do not work without a set needProducer");
throw new IllegalStateException("FactoryBots do not work without a set needProducer");
}
EventListenerContext ctx = getEventListenerContext();
BotBehaviour factoryBotInitBehaviour = new FactoryBotInitBehaviour(ctx);
BotBehaviour factoryBotHintBehaviour = new FactoryBotHintBehaviour(ctx);
BotBehaviour messageCommandBehaviour = new ExecuteWonMessageCommandBehaviour(ctx);
BotBehaviour runningBehaviour = new BotBehaviour(ctx) {
@Override
protected void onActivate(Optional<Object> message) {
initializeFactoryEventListeners();
}
};
factoryBotInitBehaviour.onDeactivateActivate(runningBehaviour, factoryBotHintBehaviour, messageCommandBehaviour);
factoryBotInitBehaviour.activate();
}
use of won.bot.framework.eventbot.EventListenerContext 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.EventListenerContext in project webofneeds by researchstudio-sat.
the class CreateEchoNeedWithFacetsAction method doRun.
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
EventListenerContext ctx = getEventListenerContext();
String replyText = "";
if (!(event instanceof NeedCreatedEventForMatcher)) {
logger.error("CreateEchoNeedWithFacetsAction can only handle NeedCreatedEventForMatcher");
return;
}
final URI reactingToNeedUri = ((NeedCreatedEventForMatcher) event).getNeedURI();
final Dataset needDataset = ((NeedCreatedEventForMatcher) event).getNeedData();
DefaultNeedModelWrapper needModelWrapper = new DefaultNeedModelWrapper(needDataset);
String titleString = needModelWrapper.getSomeTitleFromIsOrAll("en", "de");
if (titleString != null) {
replyText = titleString;
} else {
replyText = "Your Posting (" + reactingToNeedUri.toString() + ")";
}
WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService();
final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
final URI needURI = wonNodeInformationService.generateNeedURI(wonNodeUri);
needModelWrapper = new DefaultNeedModelWrapper(needURI.toString());
needModelWrapper.createContentNode(NeedContentPropertyType.IS_AND_SEEKS, needURI.toString());
needModelWrapper.setTitle(NeedContentPropertyType.IS_AND_SEEKS, "RE: " + replyText);
needModelWrapper.setDescription(NeedContentPropertyType.IS_AND_SEEKS, "This is a need automatically created by the EchoBot.");
for (URI facetUri : facets) {
needModelWrapper.addFacetUri(facetUri.toString());
}
final Dataset echoNeedDataset = needModelWrapper.copyDataset();
logger.debug("creating need on won node {} with content {} ", wonNodeUri, StringUtils.abbreviate(RdfUtils.toString(echoNeedDataset), 150));
WonMessage createNeedMessage = createWonMessage(wonNodeInformationService, needURI, wonNodeUri, echoNeedDataset);
// remember the need URI so we can react to success/failure responses
EventBotActionUtils.rememberInList(ctx, needURI, uriListName);
EventListener successCallback = new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
logger.debug("need creation successful, new need URI is {}", needURI);
// save the mapping between the original and the reaction in to the context.
getEventListenerContext().getBotContextWrapper().addUriAssociation(reactingToNeedUri, needURI);
ctx.getEventBus().publish(new NeedCreatedEvent(needURI, wonNodeUri, echoNeedDataset, null));
}
};
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 });
EventBotActionUtils.removeFromList(ctx, needURI, uriListName);
ctx.getEventBus().publish(new NeedCreationFailedEvent(wonNodeUri));
}
};
EventBotActionUtils.makeAndSubscribeResponseListener(createNeedMessage, successCallback, failureCallback, ctx);
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());
}
use of won.bot.framework.eventbot.EventListenerContext in project webofneeds by researchstudio-sat.
the class Connect2TelegramAction method doRun.
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
EventListenerContext ctx = getEventListenerContext();
if (event instanceof ConnectFromOtherNeedEvent && ctx.getBotContextWrapper() instanceof TelegramBotContextWrapper) {
TelegramBotContextWrapper botContextWrapper = (TelegramBotContextWrapper) ctx.getBotContextWrapper();
Connection con = ((ConnectFromOtherNeedEvent) event).getCon();
URI yourNeedUri = con.getNeedURI();
URI remoteNeedUri = con.getRemoteNeedURI();
Long chatId = botContextWrapper.getChatIdForURI(yourNeedUri);
if (chatId == null) {
logger.error("No chatId found for the specified needUri");
return;
}
try {
Message message = wonTelegramBotHandler.sendMessage(wonTelegramBotHandler.getTelegramMessageGenerator().getConnectMessage(chatId, remoteNeedUri, yourNeedUri));
botContextWrapper.addMessageIdWonURIRelation(message.getMessageId(), new WonURI(con.getConnectionURI(), UriType.CONNECTION));
} catch (TelegramApiException te) {
logger.error(te.getMessage());
}
}
}
use of won.bot.framework.eventbot.EventListenerContext in project webofneeds by researchstudio-sat.
the class TelegramCreateAction method doRun.
@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
EventListenerContext ctx = getEventListenerContext();
if (event instanceof TelegramCreateNeedEvent && ctx.getBotContextWrapper() instanceof TelegramBotContextWrapper) {
TelegramBotContextWrapper botContextWrapper = (TelegramBotContextWrapper) ctx.getBotContextWrapper();
TelegramCreateNeedEvent telegramCreateNeedEvent = (TelegramCreateNeedEvent) event;
String[] parameters = telegramCreateNeedEvent.getStrings();
Long chatId = telegramCreateNeedEvent.getChat().getId();
if (chatId == null) {
logger.error("no chatid present");
return;
}
try {
NeedContentPropertyType type = telegramContentExtractor.getNeedContentType(parameters[0]);
if (type == null) {
throw new InvalidParameterException("no valid type was given");
}
String title = null;
if (parameters.length > 1) {
title = parameters[1];
}
if (title == null) {
throw new InvalidParameterException("no valid title was given");
}
// MAKE THOSE ATTRIBUTES DIFFERENT AND EDITABLE
boolean isUsedForTesting = true;
boolean isDoNotMatch = false;
WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService();
final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
final URI needURI = wonNodeInformationService.generateNeedURI(wonNodeUri);
DefaultNeedModelWrapper wrapper = new DefaultNeedModelWrapper(needURI.toString());
wrapper.setTitle(type, title);
for (URI facet : facets) {
wrapper.addFacetUri(facet.toString());
}
Dataset needDataset = wrapper.copyDataset();
logger.debug("creating need on won node {} with content {} ", wonNodeUri, StringUtils.abbreviate(RdfUtils.toString(needDataset), 150));
WonMessage createNeedMessage = createWonMessage(wonNodeInformationService, needURI, wonNodeUri, needDataset, isUsedForTesting, isDoNotMatch);
EventBotActionUtils.rememberInList(ctx, needURI, uriListName);
botContextWrapper.addChatIdWonURIRelation(chatId, new WonURI(needURI, UriType.NEED));
botContextWrapper.addURIChatIdRelation(needURI, chatId);
EventListener successCallback = new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
logger.debug("need creation successful, new need URI is {}", needURI);
logger.debug("created need was from sender: " + botContextWrapper.getChatIdForURI(needURI));
try {
Message message = telegramCreateNeedEvent.getAbsSender().sendMessage(wonTelegramBotHandler.getTelegramMessageGenerator().getCreatedNeedMessage(chatId, needURI));
botContextWrapper.addMessageIdWonURIRelation(message.getMessageId(), new WonURI(needURI, UriType.NEED));
} catch (TelegramApiException te) {
logger.error(te.getMessage());
}
}
};
EventListener failureCallback = new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
String textMessage = WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) event).getFailureMessage());
logger.error("need creation failed for need URI {}, original message URI {}: {}", new Object[] { needURI, ((FailureResponseEvent) event).getOriginalMessageURI(), textMessage });
EventBotActionUtils.removeFromList(getEventListenerContext(), needURI, uriListName);
}
};
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());
} catch (Exception e) {
try {
logger.error(e.getMessage());
telegramCreateNeedEvent.getAbsSender().sendMessage(wonTelegramBotHandler.getTelegramMessageGenerator().getErrorMessage(chatId));
} catch (TelegramApiException te) {
logger.error(te.getMessage());
}
}
}
}
Aggregations