Search in sources :

Example 1 with WonMessage

use of won.protocol.message.WonMessage in project webofneeds by researchstudio-sat.

the class TwoPhaseCommitNoVoteDeactivateAllNeedsAction method doRun.

@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
    // check the global COORDINATION_MESSAGE (must be ABORT)
    if (event instanceof CloseFromOtherNeedEvent) {
        WonMessage wonMessage = ((CloseFromOtherNeedEvent) event).getWonMessage();
        NodeIterator ni = RdfUtils.visitFlattenedToNodeIterator(wonMessage.getMessageContent(), new RdfUtils.ModelVisitor<NodeIterator>() {

            @Override
            public NodeIterator visit(final Model model) {
                return model.listObjectsOfProperty(model.createProperty(WON_TX.COORDINATION_MESSAGE.getURI()));
            }
        });
        if (ni.hasNext()) {
            String coordinationMessageUri = ni.toList().get(0).asResource().getURI().toString();
            if (coordinationMessageUri.equals(WON_TX.COORDINATION_MESSAGE_ABORT.getURI().toString()))
                logger.debug("Sent COORDINATION_MESSAGE: {}", coordinationMessageUri);
            else
                logger.error("Content of the COORDINATION_MESSAGE must be: {}. Currently it is: {}", WON_TX.COORDINATION_MESSAGE_ABORT.getURI(), coordinationMessageUri);
        }
    }
    Collection<URI> toDeactivate = getEventListenerContext().getBotContext().retrieveAllNeedUris();
    for (URI uri : toDeactivate) {
        getEventListenerContext().getWonMessageSender().sendWonMessage(createWonMessage(uri));
        getEventListenerContext().getEventBus().publish(new NeedDeactivatedEvent(uri));
    }
}
Also used : NodeIterator(org.apache.jena.rdf.model.NodeIterator) CloseFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.CloseFromOtherNeedEvent) WonMessage(won.protocol.message.WonMessage) Model(org.apache.jena.rdf.model.Model) WonRdfUtils(won.protocol.util.WonRdfUtils) RdfUtils(won.protocol.util.RdfUtils) URI(java.net.URI) NeedDeactivatedEvent(won.bot.framework.eventbot.event.impl.needlifecycle.NeedDeactivatedEvent)

Example 2 with WonMessage

use of won.protocol.message.WonMessage in project webofneeds by researchstudio-sat.

the class OpenConnectionDebugAction method doRun.

@Override
public void doRun(final Event event, EventListener executingListener) throws Exception {
    if (!(event instanceof ConnectFromOtherNeedEvent)) {
        return;
    }
    if (event instanceof WonMessageReceivedOnConnectionEvent) {
        WonMessage msg = ((WonMessageReceivedOnConnectionEvent) event).getWonMessage();
        String message = WonRdfUtils.MessageUtils.getTextMessage(msg);
        if (message == null) {
            message = "";
        }
        Matcher ignoreMatcher = PATTERN_IGNORE.matcher(message);
        if (ignoreMatcher.find()) {
            logger.debug("not reacting to incoming message of type {} as the welcome message contained 'ignore'", msg.getMessageType());
            return;
        }
        Matcher waitMatcher = PATTERN_WAIT.matcher(message);
        final boolean wait = waitMatcher.find();
        int waitSeconds = 15;
        if (wait && waitMatcher.groupCount() == 2) {
            waitSeconds = Integer.parseInt(waitMatcher.group(2));
        }
        Matcher denyMatcher = PATTERN_DENY.matcher(message);
        final boolean deny = denyMatcher.find();
        ConnectionSpecificEvent connectEvent = (ConnectionSpecificEvent) event;
        logger.debug("auto-replying to connect for connection {}", connectEvent.getConnectionURI());
        URI connectionUri = connectEvent.getConnectionURI();
        String finalWelcomeMessage = welcomeMessage;
        if (wait || deny) {
            finalWelcomeMessage = welcomeMessage + " " + (deny ? "Denying" : "Accepting") + " your request " + (wait ? " after a timeout of " + waitSeconds + " seconds" : "");
        } else {
            finalWelcomeMessage = welcomeMessage + " " + welcomeHelpMessage;
        }
        final WonMessage toSend = deny ? createCloseWonMessage(connectionUri, finalWelcomeMessage) : createOpenWonMessage(connectionUri, finalWelcomeMessage);
        Runnable task = () -> {
            getEventListenerContext().getWonMessageSender().sendWonMessage(toSend);
        };
        if (wait) {
            Date when = new Date(System.currentTimeMillis() + waitSeconds * 1000);
            getEventListenerContext().getTaskScheduler().schedule(task, when);
        } else {
            task.run();
        }
    }
}
Also used : ConnectionSpecificEvent(won.bot.framework.eventbot.event.ConnectionSpecificEvent) WonMessageReceivedOnConnectionEvent(won.bot.framework.eventbot.event.impl.wonmessage.WonMessageReceivedOnConnectionEvent) Matcher(java.util.regex.Matcher) WonMessage(won.protocol.message.WonMessage) URI(java.net.URI) ConnectFromOtherNeedEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherNeedEvent) Date(java.util.Date)

Example 3 with WonMessage

use of won.protocol.message.WonMessage 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 4 with WonMessage

use of won.protocol.message.WonMessage 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 5 with WonMessage

use of won.protocol.message.WonMessage in project webofneeds by researchstudio-sat.

the class Hint2MailParserAction method doRun.

@Override
protected void doRun(Event event, EventListener executingListener) throws Exception {
    EventListenerContext ctx = getEventListenerContext();
    if (event instanceof HintFromMatcherEvent && ctx.getBotContextWrapper() instanceof MailBotContextWrapper) {
        MailBotContextWrapper botContextWrapper = (MailBotContextWrapper) ctx.getBotContextWrapper();
        Match match = ((HintFromMatcherEvent) event).getMatch();
        WonMessage message = ((HintFromMatcherEvent) event).getWonMessage();
        URI responseTo = match.getFromNeed();
        URI remoteNeedUri = match.getToNeed();
        MimeMessage originalMail = botContextWrapper.getMimeMessageForURI(responseTo);
        logger.debug("Found a hint for URI: " + responseTo + " sending a mail to the creator: " + MailContentExtractor.getFromAddressString(originalMail));
        WonMimeMessage answerMessage = mailGenerator.createHintMail(originalMail, remoteNeedUri);
        botContextWrapper.addMailIdWonURIRelation(answerMessage.getMessageID(), new WonURI(message.getReceiverURI(), UriType.CONNECTION));
        sendChannel.send(new GenericMessage<>(answerMessage));
    }
}
Also used : EventListenerContext(won.bot.framework.eventbot.EventListenerContext) HintFromMatcherEvent(won.bot.framework.eventbot.event.impl.wonmessage.HintFromMatcherEvent) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) MailBotContextWrapper(won.bot.framework.bot.context.MailBotContextWrapper) MimeMessage(javax.mail.internet.MimeMessage) WonMessage(won.protocol.message.WonMessage) WonURI(won.bot.framework.eventbot.action.impl.mail.model.WonURI) URI(java.net.URI) Match(won.protocol.model.Match)

Aggregations

WonMessage (won.protocol.message.WonMessage)237 URI (java.net.URI)157 Test (org.junit.Test)84 Dataset (org.apache.jena.query.Dataset)70 Commit (org.springframework.test.annotation.Commit)49 Connection (won.protocol.model.Connection)34 Event (won.bot.framework.eventbot.event.Event)31 Message (org.apache.camel.Message)30 EventListener (won.bot.framework.eventbot.listener.EventListener)30 Logger (org.slf4j.Logger)26 LoggerFactory (org.slf4j.LoggerFactory)26 MethodHandles (java.lang.invoke.MethodHandles)25 Optional (java.util.Optional)23 EventBus (won.bot.framework.eventbot.bus.EventBus)23 WonMessageBuilder (won.protocol.message.builder.WonMessageBuilder)23 EventBotActionUtils (won.bot.framework.eventbot.action.EventBotActionUtils)22 Set (java.util.Set)19 BaseEventBotAction (won.bot.framework.eventbot.action.BaseEventBotAction)19 EventListenerContext (won.bot.framework.eventbot.EventListenerContext)18 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)17