Search in sources :

Example 1 with FailureResponseEvent

use of won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent in project webofneeds by researchstudio-sat.

the class EventBotActionUtils method makeAndSubscribeRemoteResponseListener.

/**
 * Creates a listener that waits for the remote response to the specified message. If a SuccessResponse is received,
 * the successCallback is executed, if a FailureResponse is received, the failureCallback is executed.
 * @param outgoingMessage
 * @param successCallback
 * @param failureCallback
 * @param context
 * @return
 */
public static EventListener makeAndSubscribeRemoteResponseListener(final WonMessage outgoingMessage, final EventListener successCallback, final EventListener failureCallback, EventListenerContext context) {
    // create an event listener that processes the remote response to the wonMessage we're about to send
    EventListener listener = new ActionOnFirstEventListener(context, OriginalMessageUriRemoteResponseEventFilter.forWonMessage(outgoingMessage), new BaseEventBotAction(context) {

        @Override
        protected void doRun(final Event event, EventListener executingListener) throws Exception {
            if (event instanceof SuccessResponseEvent) {
                successCallback.onEvent(event);
            } else if (event instanceof FailureResponseEvent) {
                failureCallback.onEvent(event);
            }
        }
    });
    context.getEventBus().subscribe(SuccessResponseEvent.class, listener);
    context.getEventBus().subscribe(FailureResponseEvent.class, listener);
    return listener;
}
Also used : SuccessResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent) SuccessResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) Event(won.bot.framework.eventbot.event.Event) ActionOnFirstEventListener(won.bot.framework.eventbot.listener.impl.ActionOnFirstEventListener) EventListener(won.bot.framework.eventbot.listener.EventListener) ActionOnFirstEventListener(won.bot.framework.eventbot.listener.impl.ActionOnFirstEventListener) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException)

Example 2 with FailureResponseEvent

use of won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent 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());
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) DefaultNeedModelWrapper(won.protocol.util.DefaultNeedModelWrapper) NeedCreationFailedEvent(won.bot.framework.eventbot.event.NeedCreationFailedEvent) Dataset(org.apache.jena.query.Dataset) NeedCreatedEventForMatcher(won.bot.framework.eventbot.event.impl.matcher.NeedCreatedEventForMatcher) WonMessage(won.protocol.message.WonMessage) WonNodeInformationService(won.protocol.service.WonNodeInformationService) NeedCreationFailedEvent(won.bot.framework.eventbot.event.NeedCreationFailedEvent) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) Event(won.bot.framework.eventbot.event.Event) NeedCreatedEvent(won.bot.framework.eventbot.event.impl.needlifecycle.NeedCreatedEvent) EventListener(won.bot.framework.eventbot.listener.EventListener) URI(java.net.URI) NeedCreatedEvent(won.bot.framework.eventbot.event.impl.needlifecycle.NeedCreatedEvent)

Example 3 with FailureResponseEvent

use of won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent 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());
            }
        }
    }
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) DefaultNeedModelWrapper(won.protocol.util.DefaultNeedModelWrapper) Message(org.telegram.telegrambots.api.objects.Message) WonMessage(won.protocol.message.WonMessage) TelegramCreateNeedEvent(won.bot.framework.eventbot.event.impl.telegram.TelegramCreateNeedEvent) Dataset(org.apache.jena.query.Dataset) WonNodeInformationService(won.protocol.service.WonNodeInformationService) NeedContentPropertyType(won.protocol.model.NeedContentPropertyType) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) URI(java.net.URI) TelegramApiException(org.telegram.telegrambots.exceptions.TelegramApiException) InvalidParameterException(java.security.InvalidParameterException) TelegramApiException(org.telegram.telegrambots.exceptions.TelegramApiException) InvalidParameterException(java.security.InvalidParameterException) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) TelegramBotContextWrapper(won.bot.framework.bot.context.TelegramBotContextWrapper) WonMessage(won.protocol.message.WonMessage) TelegramCreateNeedEvent(won.bot.framework.eventbot.event.impl.telegram.TelegramCreateNeedEvent) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) Event(won.bot.framework.eventbot.event.Event) EventListener(won.bot.framework.eventbot.listener.EventListener)

Example 4 with FailureResponseEvent

use of won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent in project webofneeds by researchstudio-sat.

the class ExecuteSendMessageCommandAction method doRun.

/**
 * Constructs the message via <code>createWonMessage</code> and registers a listener for the response from the
 * local WoN node and, if <code>messageIsSenttoRemoteNode</code> is true, a listener for the response from the
 * remote WoN node.
 * @param event
 * @param executingListener
 */
@Override
public final void doRun(Event event, EventListener executingListener) {
    T messageCommandEvent = (T) event;
    try {
        // create the message
        WonMessage message = createWonMessage(messageCommandEvent);
        if (message == null) {
            // assume that the implementation class handles logging and error event creation.
            return;
        }
        // register listeners for the ResponseMessage generated by the own WoN node
        EventBotActionUtils.makeAndSubscribeResponseListener(message, responseEvent -> {
            if (responseEvent instanceof SuccessResponseEvent) {
                SuccessResponseEvent successEvent = (SuccessResponseEvent) responseEvent;
                logger.debug(makeLogMessageString(event) + " succeeded on local WoN node");
                Event eventToPublish = createLocalNodeSuccessEvent(messageCommandEvent, message, successEvent);
                if (eventToPublish != null) {
                    getEventListenerContext().getEventBus().publish(eventToPublish);
                }
            }
        }, responseEvent -> {
            if (responseEvent instanceof FailureResponseEvent) {
                FailureResponseEvent failureEvent = (FailureResponseEvent) responseEvent;
                logger.info(makeLogMessageString(event) + " failed on local WoN node with message: {}", WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) responseEvent).getFailureMessage()));
                Event eventToPublish = createLocalNodeFailureEvent(messageCommandEvent, message, failureEvent);
                if (eventToPublish != null) {
                    getEventListenerContext().getEventBus().publish(eventToPublish);
                }
            }
        }, getEventListenerContext());
        // register listeners for the ResponseMessage generated by the remote WoN node
        if (messageIsSentToRemoteNode) {
            EventBotActionUtils.makeAndSubscribeRemoteResponseListener(message, responseEvent -> {
                if (responseEvent instanceof SuccessResponseEvent) {
                    SuccessResponseEvent successEvent = (SuccessResponseEvent) responseEvent;
                    logger.debug(makeLogMessageString(event) + " succeeded on remote WoN node");
                    Event eventToPublish = createRemoteNodeSuccessEvent(messageCommandEvent, message, successEvent);
                    if (eventToPublish != null) {
                        getEventListenerContext().getEventBus().publish(eventToPublish);
                    }
                }
            }, responseEvent -> {
                if (responseEvent instanceof FailureResponseEvent) {
                    FailureResponseEvent failureEvent = (FailureResponseEvent) responseEvent;
                    logger.info(makeLogMessageString(event) + " failed on remote WoN node with message: {}", WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) responseEvent).getFailureMessage()));
                    Event eventToPublish = createRemoteNodeFailureEvent(messageCommandEvent, message, failureEvent);
                    if (eventToPublish != null) {
                        getEventListenerContext().getEventBus().publish(eventToPublish);
                    }
                }
            }, getEventListenerContext());
        }
        // send the message
        getEventListenerContext().getWonMessageSender().sendWonMessage(message);
        if (logger.isDebugEnabled()) {
            logger.debug(makeLogMessageString(event));
        }
    } catch (Exception e) {
        logger.warn("error executing messageCommandEvent: ", e);
        getEventListenerContext().getEventBus().publish(createMessageNotSentEvent(messageCommandEvent, e.getMessage()));
    }
}
Also used : SuccessResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent) WonMessage(won.protocol.message.WonMessage) RemoteNeedSpecificEvent(won.bot.framework.eventbot.event.RemoteNeedSpecificEvent) MessageCommandEvent(won.bot.framework.eventbot.event.impl.command.MessageCommandEvent) SuccessResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent) ConnectionSpecificEvent(won.bot.framework.eventbot.event.ConnectionSpecificEvent) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) MessageCommandSuccessEvent(won.bot.framework.eventbot.event.impl.command.MessageCommandSuccessEvent) MessageCommandFailureEvent(won.bot.framework.eventbot.event.impl.command.MessageCommandFailureEvent) Event(won.bot.framework.eventbot.event.Event) NeedSpecificEvent(won.bot.framework.eventbot.event.NeedSpecificEvent) MessageCommandNotSentEvent(won.bot.framework.eventbot.event.impl.command.MessageCommandNotSentEvent) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) WonMessageBuilderException(won.protocol.exception.WonMessageBuilderException)

Example 5 with FailureResponseEvent

use of won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent in project webofneeds by researchstudio-sat.

the class CreateNeedFromMailAction method doRun.

protected void doRun(Event event, EventListener executingListener) throws Exception {
    EventListenerContext ctx = getEventListenerContext();
    if (event instanceof CreateNeedFromMailEvent && ctx.getBotContextWrapper() instanceof MailBotContextWrapper) {
        MailBotContextWrapper botContextWrapper = (MailBotContextWrapper) ctx.getBotContextWrapper();
        MimeMessage message = ((CreateNeedFromMailEvent) event).getMessage();
        try {
            NeedContentPropertyType type = mailContentExtractor.getNeedType(message);
            String title = mailContentExtractor.getTitle(message);
            String description = mailContentExtractor.getDescription(message);
            String[] tags = mailContentExtractor.getTags(message);
            boolean isUsedForTesting = mailContentExtractor.isUsedForTesting(message);
            boolean isDoNotMatch = mailContentExtractor.isDoNotMatch(message);
            WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService();
            final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
            final URI needURI = wonNodeInformationService.generateNeedURI(wonNodeUri);
            DefaultNeedModelWrapper needModelWrapper = new DefaultNeedModelWrapper(needURI.toString());
            needModelWrapper.setTitle(type, title);
            needModelWrapper.setDescription(type, description);
            for (String tag : tags) {
                needModelWrapper.addTag(type, tag);
            }
            for (URI facet : facets) {
                needModelWrapper.addFacetUri(facet.toString());
            }
            Dataset dataset = needModelWrapper.copyDataset();
            logger.debug("creating need on won node {} with content {} ", wonNodeUri, StringUtils.abbreviate(RdfUtils.toString(dataset), 150));
            WonMessage createNeedMessage = createWonMessage(wonNodeInformationService, needURI, wonNodeUri, dataset, isUsedForTesting, isDoNotMatch);
            EventBotActionUtils.rememberInList(ctx, needURI, uriListName);
            botContextWrapper.addUriMimeMessageRelation(needURI, message);
            EventListener successCallback = new EventListener() {

                @Override
                public void onEvent(Event event) throws Exception {
                    logger.debug("need creation successful, new need URI is {}", needURI);
                    String sender = MailContentExtractor.getFromAddressString(botContextWrapper.getMimeMessageForURI(needURI));
                    botContextWrapper.addMailAddressWonURIRelation(sender, new WonURI(needURI, UriType.NEED));
                    logger.debug("created need was from sender: " + sender);
                }
            };
            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);
                    botContextWrapper.removeUriMimeMessageRelation(needURI);
                }
            };
            EventBotActionUtils.makeAndSubscribeResponseListener(createNeedMessage, successCallback, failureCallback, ctx);
            logger.debug("registered listeners for response to message URI {}", createNeedMessage.getMessageURI());
            ctx.getWonMessageSender().sendWonMessage(createNeedMessage);
            logger.debug("need creation message sent with message URI {}", createNeedMessage.getMessageURI());
        } catch (MessagingException me) {
            logger.error("messaging exception occurred: {}", me);
        }
    }
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) DefaultNeedModelWrapper(won.protocol.util.DefaultNeedModelWrapper) MailBotContextWrapper(won.bot.framework.bot.context.MailBotContextWrapper) MessagingException(javax.mail.MessagingException) Dataset(org.apache.jena.query.Dataset) WonNodeInformationService(won.protocol.service.WonNodeInformationService) NeedContentPropertyType(won.protocol.model.NeedContentPropertyType) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) URI(java.net.URI) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) MimeMessage(javax.mail.internet.MimeMessage) WonMessage(won.protocol.message.WonMessage) CreateNeedFromMailEvent(won.bot.framework.eventbot.event.impl.mail.CreateNeedFromMailEvent) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) Event(won.bot.framework.eventbot.event.Event) EventListener(won.bot.framework.eventbot.listener.EventListener) CreateNeedFromMailEvent(won.bot.framework.eventbot.event.impl.mail.CreateNeedFromMailEvent)

Aggregations

Event (won.bot.framework.eventbot.event.Event)10 FailureResponseEvent (won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent)10 EventListener (won.bot.framework.eventbot.listener.EventListener)9 WonMessage (won.protocol.message.WonMessage)8 URI (java.net.URI)7 WonNodeInformationService (won.protocol.service.WonNodeInformationService)7 Dataset (org.apache.jena.query.Dataset)6 EventListenerContext (won.bot.framework.eventbot.EventListenerContext)6 DefaultNeedModelWrapper (won.protocol.util.DefaultNeedModelWrapper)4 MessagingException (javax.mail.MessagingException)3 NeedCreationFailedEvent (won.bot.framework.eventbot.event.NeedCreationFailedEvent)3 NeedCreatedEvent (won.bot.framework.eventbot.event.impl.needlifecycle.NeedCreatedEvent)3 SuccessResponseEvent (won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent)3 IOException (java.io.IOException)2 Resource (org.apache.jena.rdf.model.Resource)2 WonURI (won.bot.framework.eventbot.action.impl.mail.model.WonURI)2 EventBus (won.bot.framework.eventbot.bus.EventBus)2 NeedSpecificEvent (won.bot.framework.eventbot.event.NeedSpecificEvent)2 NeedCreatedEventForMatcher (won.bot.framework.eventbot.event.impl.matcher.NeedCreatedEventForMatcher)2 ActionOnFirstEventListener (won.bot.framework.eventbot.listener.impl.ActionOnFirstEventListener)2