Search in sources :

Example 1 with ConnectFromOtherAtomEvent

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

the class ServiceAtomBehaviour method onActivate.

@Override
protected void onActivate(Optional<Object> message) {
    logger.debug("activating ServiceAtomBehaviour");
    final EventListenerContext ctx = this.context;
    subscribeWithAutoCleanup(InitializeEvent.class, new ActionOnEventListener(ctx, new AbstractCreateAtomAction(ctx) {

        @Override
        protected void doRun(Event event, EventListener executingListener) throws Exception {
            logger.debug("Initializing the BotServiceAtom...");
            URI serviceAtomUri = serviceAtomContext.getServiceAtomUri();
            if (serviceAtomUri == null) {
                logger.debug("BotServiceAtom does not exist, creating a new one...");
                createServiceAtom();
            } else {
                logger.debug("BotServiceAtom exists atomUri: {} checking validity...", serviceAtomUri);
                Dataset serviceBotDataSet = ctx.getLinkedDataSource().getDataForPublicResource(serviceAtomUri);
                if (serviceBotDataSet == null) {
                    logger.debug("BotServiceAtom can't be retrieved, creating a new one...");
                    createServiceAtom();
                } else {
                    ServiceAtomModelWrapper oldServiceAtomWrapper = new ServiceAtomModelWrapper(serviceBotDataSet);
                    if (!Objects.equals(oldServiceAtomWrapper.getServiceAtomContent(), serviceAtomContent)) {
                        logger.debug("BotServiceAtom is outdated, modifying the BotServiceAtom");
                        modifyServiceAtom(oldServiceAtomWrapper);
                    } else {
                        logger.info("#####################################################################################");
                        logger.info("BotServiceAtom is still up to date, atom URI is {}", serviceAtomUri);
                        logger.info("#####################################################################################");
                    }
                }
            }
        }

        private void createServiceAtom() {
            final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
            WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService();
            final URI atomUri = wonNodeInformationService.generateAtomURI(wonNodeUri);
            Dataset botServiceDataset = new ServiceAtomModelWrapper(atomUri, serviceAtomContent).copyDataset();
            logger.debug("creating BotServiceAtom on won node {} with content: {} ", wonNodeUri, RdfUtils.toString(Prefixer.setPrefixes(botServiceDataset)));
            WonMessage createAtomMessage = createWonMessage(atomUri, botServiceDataset);
            createAtomMessage = ctx.getWonMessageSender().prepareMessage(createAtomMessage);
            ctx.getBotContextWrapper().rememberAtomUri(atomUri);
            EventBus bus = ctx.getEventBus();
            EventListener successCallback = event -> {
                logger.info("#####################################################################################");
                logger.info("BotServiceAtom creation successful, new atom URI is {}", atomUri);
                logger.info("#####################################################################################");
                serviceAtomContext.setServiceAtomUri(atomUri);
                bus.publish(new AtomCreatedEvent(atomUri, wonNodeUri, botServiceDataset, null));
            };
            EventListener failureCallback = event -> {
                String textMessage = WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) event).getFailureMessage());
                logger.error("BotServiceAtom creation failed for atom URI {}, original message URI: {}", atomUri, textMessage);
                ctx.getBotContextWrapper().removeAtomUri(atomUri);
            };
            EventBotActionUtils.makeAndSubscribeResponseListener(createAtomMessage, successCallback, failureCallback, ctx);
            logger.debug("registered listeners for response to message URI {}", createAtomMessage.getMessageURI());
            ctx.getWonMessageSender().sendMessage(createAtomMessage);
            logger.debug("BotServiceAtom creation message sent with message URI {}", createAtomMessage.getMessageURI());
        }

        private void modifyServiceAtom(ServiceAtomModelWrapper oldServiceAtomModelWrapper) {
            final URI atomUri = URI.create(oldServiceAtomModelWrapper.getAtomUri());
            // Replace placeholder socketUris with existing socketUris
            // if socketType was present before modification
            Map<String, String> oldServiceAtomSocketsInverse = oldServiceAtomModelWrapper.getServiceAtomContent().getSockets().entrySet().stream().collect(Collectors.toMap(socketEntry -> socketEntry.getValue(), socketEntry -> socketEntry.getKey()));
            serviceAtomContent.setSockets(serviceAtomContent.getSockets().entrySet().stream().collect(Collectors.toMap(socketEntry -> oldServiceAtomSocketsInverse.containsKey(socketEntry.getValue()) ? oldServiceAtomSocketsInverse.get(socketEntry.getValue()) : socketEntry.getKey(), socketEntry -> socketEntry.getValue())));
            ServiceAtomModelWrapper serviceAtomModelWrapper = new ServiceAtomModelWrapper(atomUri, serviceAtomContent);
            final URI wonNodeUri = URI.create(oldServiceAtomModelWrapper.getWonNodeUri());
            Dataset botServiceDataset = serviceAtomModelWrapper.copyDataset();
            logger.debug("creating BotServiceAtom on won node {} with content: {} ", wonNodeUri, RdfUtils.toString(Prefixer.setPrefixes(botServiceDataset)));
            RdfUtils.replaceBaseURI(botServiceDataset, atomUri.toString(), true);
            ServiceAtomModelWrapper modifiedAtomModelWrapper = new ServiceAtomModelWrapper(botServiceDataset);
            WonMessage modifyAtomMessage = WonMessageBuilder.replace().atom(atomUri).content().dataset(modifiedAtomModelWrapper.copyDatasetWithoutSysinfo()).build();
            modifyAtomMessage = ctx.getWonMessageSender().prepareMessage(modifyAtomMessage);
            ctx.getBotContextWrapper().rememberAtomUri(atomUri);
            EventBus bus = ctx.getEventBus();
            EventListener successCallback = event -> {
                logger.info("#####################################################################################");
                logger.info("BotServiceAtom modification successful, atom URI is {}", atomUri);
                logger.info("#####################################################################################");
                serviceAtomContext.setServiceAtomUri(atomUri);
                bus.publish(new AtomCreatedEvent(atomUri, wonNodeUri, botServiceDataset, null));
            };
            EventListener failureCallback = event -> {
                String textMessage = WonRdfUtils.MessageUtils.getTextMessage(((FailureResponseEvent) event).getFailureMessage());
                logger.error("BotServiceAtom modification failed for atom URI {}, original message URI: {}", atomUri, textMessage);
                ctx.getBotContextWrapper().removeAtomUri(atomUri);
            };
            EventBotActionUtils.makeAndSubscribeResponseListener(modifyAtomMessage, successCallback, failureCallback, ctx);
            logger.debug("registered listeners for response to message URI {}", modifyAtomMessage.getMessageURI());
            ctx.getWonMessageSender().sendMessage(modifyAtomMessage);
            logger.debug("BotServiceAtom creation message sent with message URI {}", modifyAtomMessage.getMessageURI());
        }
    }));
    subscribeWithAutoCleanup(AtomCreatedEvent.class, new ActionOnEventListener(ctx, new BaseEventBotAction(ctx) {

        @Override
        protected void doRun(Event event, EventListener executingListener) throws Exception {
            if (event instanceof AtomCreatedEvent) {
                AtomCreatedEvent atomCreatedEvent = (AtomCreatedEvent) event;
                URI botServiceAtomUri = serviceAtomContext.getServiceAtomUri();
                URI createdAtomUri = atomCreatedEvent.getAtomURI();
                if (!Objects.equals(createdAtomUri, botServiceAtomUri)) {
                    if (ctx.getBotContextWrapper().isAtomKnown(createdAtomUri)) {
                        logger.debug("Atom ({}) is known, must be one we created..., dataset: {}", createdAtomUri, RdfUtils.toString(Prefixer.setPrefixes(atomCreatedEvent.getAtomDataset())));
                        Optional<URI> createdAtomHoldableSocketUri = WonLinkedDataUtils.getSocketsOfType(createdAtomUri, WXHOLD.HoldableSocket.asURI(), ctx.getLinkedDataSource()).stream().findFirst();
                        if (createdAtomHoldableSocketUri.isPresent()) {
                            logger.debug("Atom ({}) has the holdableSocket, connect botServiceAtom ({}) with this atom", createdAtomUri, botServiceAtomUri);
                            Optional<URI> botServiceAtomHolderSocketUri = WonLinkedDataUtils.getSocketsOfType(botServiceAtomUri, WXHOLD.HolderSocket.asURI(), ctx.getLinkedDataSource()).stream().findFirst();
                            logger.debug("Connecting atom ({}) - botServiceAtom ({})", createdAtomUri, botServiceAtomUri);
                            URI senderSocketURI = createdAtomHoldableSocketUri.orElseThrow(() -> new IllegalStateException("no suitable socket for connecting on created atom " + createdAtomUri));
                            URI recipientSocketURI = botServiceAtomHolderSocketUri.orElseThrow(() -> new IllegalStateException("no suitable socket for connecting on bot service atom " + botServiceAtomUri));
                            WonMessage connectToServiceAtomMessage = WonMessageBuilder.connect().sockets().sender(senderSocketURI).recipient(recipientSocketURI).content().text("Automated Connect to Service Atom").build();
                            ctx.getWonMessageSender().prepareAndSendMessage(connectToServiceAtomMessage);
                        } else {
                            logger.debug("Atom ({}) does not have a holdable Socket, no connect action required", createdAtomUri);
                        }
                    } else {
                        logger.debug("Atom ({}) is not known, must be someone elses...", createdAtomUri);
                    }
                } else {
                    logger.debug("BotServiceAtomCreated, no connect action required");
                }
            }
        }
    }));
    subscribeWithAutoCleanup(ConnectFromOtherAtomEvent.class, new ActionOnEventListener(ctx, new BaseEventBotAction(ctx) {

        @Override
        protected void doRun(Event event, EventListener executingListener) throws Exception {
            if (event instanceof ConnectFromOtherAtomEvent) {
                ConnectFromOtherAtomEvent connectFromOtherAtomEvent = (ConnectFromOtherAtomEvent) event;
                URI botServiceAtomUri = serviceAtomContext.getServiceAtomUri();
                URI senderAtomUri = connectFromOtherAtomEvent.getWonMessage().getSenderAtomURI();
                URI targetAtomUri = connectFromOtherAtomEvent.getWonMessage().getRecipientAtomURI();
                logger.debug("Possibly accept the connection Request with holderFacet<->holdableFacet if atom is BotServiceAtom");
                if (ctx.getBotContextWrapper().isAtomKnown(senderAtomUri) && ctx.getBotContextWrapper().isAtomKnown(targetAtomUri) && Objects.equals(targetAtomUri, botServiceAtomUri)) {
                    logger.debug("Both Atoms belong to you, you might want to accept the connect, socketUri: {}, targetSocketUri: {}", connectFromOtherAtomEvent.getWonMessage().getSenderSocketURI(), connectFromOtherAtomEvent.getWonMessage().getRecipientSocketURI());
                    URI senderSocketUri = connectFromOtherAtomEvent.getWonMessage().getSenderSocketURI();
                    URI targetSocketUri = connectFromOtherAtomEvent.getWonMessage().getRecipientSocketURI();
                    Optional<URI> senderSocketTypeUri = WonLinkedDataUtils.getTypeOfSocket(senderSocketUri, ctx.getLinkedDataSource());
                    Optional<URI> targetSocketTypeUri = WonLinkedDataUtils.getTypeOfSocket(targetSocketUri, ctx.getLinkedDataSource());
                    if (senderSocketTypeUri.isPresent() && targetSocketTypeUri.isPresent() && Objects.equals(senderSocketTypeUri.get(), WXHOLD.HoldableSocket.asURI()) && Objects.equals(targetSocketTypeUri.get(), WXHOLD.HolderSocket.asURI())) {
                        logger.debug("Accepting connect request from atom ({}) to serviceAtom ({})", senderAtomUri, targetAtomUri);
                        WonMessage openServiceAtomMessage = WonMessageBuilder.connect().sockets().reactingTo(connectFromOtherAtomEvent.getWonMessage()).direction().fromOwner().content().text("Automated Open from Service Atom").build();
                        ctx.getWonMessageSender().prepareAndSendMessage(openServiceAtomMessage);
                    }
                } else {
                    logger.debug("At least one of the two Atoms is not known, or the targetAtomUri is not the botServiceAtomUri, ignore the connect request");
                }
            }
        }
    }));
}
Also used : AtomCreatedEvent(won.bot.framework.eventbot.event.impl.atomlifecycle.AtomCreatedEvent) LoggerFactory(org.slf4j.LoggerFactory) EventBus(won.bot.framework.eventbot.bus.EventBus) ConnectFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherAtomEvent) WonMessage(won.protocol.message.WonMessage) InitializeEvent(won.bot.framework.eventbot.event.impl.lifecycle.InitializeEvent) WonMessageBuilder(won.protocol.message.builder.WonMessageBuilder) WXHOLD(won.protocol.vocabulary.WXHOLD) Map(java.util.Map) URI(java.net.URI) Dataset(org.apache.jena.query.Dataset) EventListenerContext(won.bot.framework.eventbot.EventListenerContext) WonNodeInformationService(won.protocol.service.WonNodeInformationService) Logger(org.slf4j.Logger) WonLinkedDataUtils(won.protocol.util.linkeddata.WonLinkedDataUtils) Prefixer(won.protocol.util.Prefixer) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) BotBehaviour(won.bot.framework.eventbot.behaviour.BotBehaviour) MethodHandles(java.lang.invoke.MethodHandles) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) EventBotActionUtils(won.bot.framework.eventbot.action.EventBotActionUtils) AbstractCreateAtomAction(won.bot.framework.eventbot.action.impl.atomlifecycle.AbstractCreateAtomAction) Collectors(java.util.stream.Collectors) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) WonRdfUtils(won.protocol.util.WonRdfUtils) Objects(java.util.Objects) Event(won.bot.framework.eventbot.event.Event) RdfUtils(won.protocol.util.RdfUtils) Optional(java.util.Optional) EventListener(won.bot.framework.eventbot.listener.EventListener) EventListenerContext(won.bot.framework.eventbot.EventListenerContext) Dataset(org.apache.jena.query.Dataset) WonNodeInformationService(won.protocol.service.WonNodeInformationService) AbstractCreateAtomAction(won.bot.framework.eventbot.action.impl.atomlifecycle.AbstractCreateAtomAction) EventBus(won.bot.framework.eventbot.bus.EventBus) URI(java.net.URI) AtomCreatedEvent(won.bot.framework.eventbot.event.impl.atomlifecycle.AtomCreatedEvent) ConnectFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherAtomEvent) WonMessage(won.protocol.message.WonMessage) AtomCreatedEvent(won.bot.framework.eventbot.event.impl.atomlifecycle.AtomCreatedEvent) ConnectFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherAtomEvent) InitializeEvent(won.bot.framework.eventbot.event.impl.lifecycle.InitializeEvent) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) Event(won.bot.framework.eventbot.event.Event) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) EventListener(won.bot.framework.eventbot.listener.EventListener) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent)

Example 2 with ConnectFromOtherAtomEvent

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

the class AclTests method testAutoConnectByAcl.

@Test(timeout = 60 * 1000)
public void testAutoConnectByAcl() throws Exception {
    runTest(ctx -> {
        EventBus bus = ctx.getEventBus();
        final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
        final URI atomUri1 = ctx.getWonNodeInformationService().generateAtomURI(wonNodeUri);
        final URI atomUri2 = ctx.getWonNodeInformationService().generateAtomURI(wonNodeUri);
        final BotBehaviour bbCreateAtom1 = new BotBehaviour(ctx, "bbCreateAtom1") {

            @Override
            protected void onActivate(Optional<Object> message) {
                final String atomUriString = atomUri1.toString();
                final AtomContent atomContent = AtomContent.builder(atomUriString).addTitle("Autoconnecting atom").addSocket(Socket.builder(atomUriString + "#chatSocket").setSocketDefinition(WXCHAT.ChatSocket.asURI()).build()).addType(URI.create(WON.Atom.getURI())).build();
                Authorization auth = Authorization.builder().addGranteesAtomExpression(ae -> ae.addAtomsURI(atomUri2)).addGrant(ase -> ase.addGraph(ge -> ge.addOperationsSimpleOperationExpression(OP_READ)).addSocket(s -> s.addSocketType(WXCHAT.ChatSocket.asURI())).addOperationsSimpleOperationExpression(OP_AUTO_CONNECT)).build();
                WonMessage createMessage = WonMessageBuilder.createAtom().atom(atomUri1).content().graph(RdfOutput.toGraph(atomContent)).content().aclGraph(won.auth.model.RdfOutput.toGraph(auth)).content().aclGraph(won.auth.model.RdfOutput.toGraph(getAnyoneMayConnectAuth())).content().aclGraph(won.auth.model.RdfOutput.toGraph(getConnectedMayCommunicateAuth())).build();
                createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
                ctx.getBotContextWrapper().rememberAtomUri(atomUri1);
                EventListener successCallback = event -> {
                    logger.debug("Connection autoconnecting atom created");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Create autoconnecting atom");
                EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(createMessage);
            }
        };
        // create match source
        final BotBehaviour bbCreateAtom2 = new BotBehaviour(ctx, "bbCreateAtom2") {

            @Override
            protected void onActivate(Optional<Object> message) {
                final String atomUriString = atomUri2.toString();
                final AtomContent atomContent = AtomContent.builder(atomUriString).addTitle("Connecting atom").addSocket(Socket.builder(atomUriString + "#chatSocket").setSocketDefinition(WXCHAT.ChatSocket.asURI()).build()).addType(URI.create(WON.Atom.getURI())).build();
                Authorization auth = Authorization.builder().addGranteesAtomExpression(ae -> ae.addAtomsURI(atomUri1)).addGrant(ase -> ase.addGraph(ge -> ge.addOperationsSimpleOperationExpression(OP_READ))).build();
                WonMessage createMessage = WonMessageBuilder.createAtom().atom(atomUri2).content().graph(RdfOutput.toGraph(atomContent)).content().aclGraph(won.auth.model.RdfOutput.toGraph(auth)).content().aclGraph(won.auth.model.RdfOutput.toGraph(getAnyoneMayConnectAuth())).content().aclGraph(won.auth.model.RdfOutput.toGraph(getConnectedMayCommunicateAuth())).build();
                createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
                ctx.getBotContextWrapper().rememberAtomUri(atomUri2);
                EventListener successCallback = event -> {
                    logger.debug("Connection initiating atom created");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Create connection initiating  atom");
                EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(createMessage);
            }
        };
        BotBehaviour bbSendConnect = new BotBehaviour(ctx, "bbSendConnect") {

            @Override
            protected void onActivate(Optional<Object> message) {
                WonMessage connectMessage = WonMessageBuilder.connect().sockets().sender(URI.create(atomUri2.toString() + "#chatSocket")).recipient(URI.create(atomUri1.toString() + "#chatSocket")).direction().fromOwner().content().text("Hello there!").build();
                connectMessage = ctx.getWonMessageSender().prepareMessage(connectMessage);
                EventListener successCallback = event -> {
                    logger.debug("Connection requested");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Requesting connection");
                EventBotActionUtils.makeAndSubscribeResponseListener(connectMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(connectMessage);
            }
        };
        BotBehaviour bbWaitForConnectFromAtom1 = new BotBehaviour(ctx, "bbWaitForConnectFromAtom1") {

            @Override
            protected void onActivate(Optional<Object> message) {
                bus.subscribe(ConnectFromOtherAtomEvent.class, new EventFilter() {

                    @Override
                    public boolean accept(Event event) {
                        return event instanceof ConnectFromOtherAtomEvent && ((ConnectFromOtherAtomEvent) event).getSenderSocket().equals(URI.create(atomUri1.toString() + "#chatSocket"));
                    }
                }, new BaseEventBotAction(ctx) {

                    @Override
                    protected void doRun(Event event, EventListener executingListener) throws Exception {
                        passTest(bus);
                    }
                });
            }
        };
        BehaviourBarrier barrier = new BehaviourBarrier(ctx);
        barrier.waitFor(bbCreateAtom1, bbCreateAtom2);
        barrier.thenStart(bbSendConnect);
        barrier.activate();
        bbCreateAtom1.activate();
        bbCreateAtom2.activate();
        bbWaitForConnectFromAtom1.activate();
    });
}
Also used : EventBotAction(won.bot.framework.eventbot.action.EventBotAction) SuccessResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent) LoggerFactory(org.slf4j.LoggerFactory) won.auth.model(won.auth.model) EventBus(won.bot.framework.eventbot.bus.EventBus) CachingLinkedDataSource(won.protocol.util.linkeddata.CachingLinkedDataSource) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ConnectFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherAtomEvent) BehaviourBarrier(won.bot.framework.eventbot.behaviour.BehaviourBarrier) ContentUtils(won.utils.content.ContentUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) WonMessage(won.protocol.message.WonMessage) HashSet(java.util.HashSet) WonMessageBuilder(won.protocol.message.builder.WonMessageBuilder) MessageFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.MessageFromOtherAtomEvent) ActionOnceAfterNEventsListener(won.bot.framework.eventbot.listener.impl.ActionOnceAfterNEventsListener) Shacl2JavaInstanceFactory(won.shacl2java.Shacl2JavaInstanceFactory) Individuals(won.auth.model.Individuals) URI(java.net.URI) Dataset(org.apache.jena.query.Dataset) Socket(won.utils.content.model.Socket) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) BotBehaviour(won.bot.framework.eventbot.behaviour.BotBehaviour) MethodHandles(java.lang.invoke.MethodHandles) RdfOutput(won.utils.content.model.RdfOutput) Set(java.util.Set) Test(org.junit.Test) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) EventBotActionUtils(won.bot.framework.eventbot.action.EventBotActionUtils) LinkedDataFetchingException(won.protocol.rest.LinkedDataFetchingException) AtomContent(won.utils.content.model.AtomContent) AuthEnabledLinkedDataSource(won.auth.linkeddata.AuthEnabledLinkedDataSource) CountDownLatch(java.util.concurrent.CountDownLatch) Event(won.bot.framework.eventbot.event.Event) won.protocol.vocabulary(won.protocol.vocabulary) Optional(java.util.Optional) EventFilter(won.bot.framework.eventbot.filter.EventFilter) EventListener(won.bot.framework.eventbot.listener.EventListener) Assert(org.junit.Assert) GraphFactory(org.apache.jena.sparql.graph.GraphFactory) BotBehaviour(won.bot.framework.eventbot.behaviour.BotBehaviour) Optional(java.util.Optional) BehaviourBarrier(won.bot.framework.eventbot.behaviour.BehaviourBarrier) EventBus(won.bot.framework.eventbot.bus.EventBus) URI(java.net.URI) EventFilter(won.bot.framework.eventbot.filter.EventFilter) LinkedDataFetchingException(won.protocol.rest.LinkedDataFetchingException) ConnectFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherAtomEvent) WonMessage(won.protocol.message.WonMessage) SuccessResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent) ConnectFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherAtomEvent) MessageFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.MessageFromOtherAtomEvent) Event(won.bot.framework.eventbot.event.Event) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) EventListener(won.bot.framework.eventbot.listener.EventListener) AtomContent(won.utils.content.model.AtomContent) Test(org.junit.Test)

Example 3 with ConnectFromOtherAtomEvent

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

the class OpenConnectionAction method doRun.

@Override
public void doRun(final Event event, EventListener executingListener) throws Exception {
    if (event instanceof ConnectFromOtherAtomEvent) {
        ConnectFromOtherAtomEvent connectEvent = (ConnectFromOtherAtomEvent) event;
        logger.debug("auto-replying to connect for connection {}", connectEvent.getConnectionURI());
        getEventListenerContext().getWonMessageSender().prepareAndSendMessage(createConnectWonMessage(connectEvent.getAtomURI(), connectEvent.getTargetAtomURI(), connectEvent.getRecipientSocket(), connectEvent.getSenderSocket()));
    } else if (event instanceof AtomHintFromMatcherEvent) {
        // TODO: the hint with a match object is not really suitable here. Would be
        // better to
        // use connection object instead
        AtomHintFromMatcherEvent hintEvent = (AtomHintFromMatcherEvent) event;
        logger.debug("ignore opening connection based on atom hint {} not possible", hintEvent);
    } else if (event instanceof SocketHintFromMatcherEvent) {
        // TODO: the hint with a match object is not really suitable here. Would be
        // better to
        // use connection object instead
        SocketHintFromMatcherEvent hintEvent = (SocketHintFromMatcherEvent) event;
        Optional<URI> recipientAtom = Optional.of(hintEvent.getRecipientAtom());
        Optional<URI> hintTargetAtom = Optional.of(hintEvent.getHintTargetAtom());
        if (!recipientAtom.isPresent()) {
            logger.info("could not get recipient atom for hint event {}, cannot connect", event);
            return;
        }
        if (!hintTargetAtom.isPresent()) {
            logger.info("could not get target atom for hint event {}, cannot connect", event);
            return;
        }
        logger.debug("opening connection based on hint {}", event);
        getEventListenerContext().getWonMessageSender().prepareAndSendMessage(createConnectWonMessage(recipientAtom.get(), hintTargetAtom.get(), hintEvent.getRecipientSocket(), (hintEvent.getHintTargetSocket())));
    }
}
Also used : ConnectFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherAtomEvent) SocketHintFromMatcherEvent(won.bot.framework.eventbot.event.impl.wonmessage.SocketHintFromMatcherEvent) URI(java.net.URI) AtomHintFromMatcherEvent(won.bot.framework.eventbot.event.impl.wonmessage.AtomHintFromMatcherEvent)

Example 4 with ConnectFromOtherAtomEvent

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

the class AclTests method testGroupChat.

@Test(timeout = 60 * 1000)
public void testGroupChat() throws Exception {
    runTest(ctx -> {
        EventBus bus = ctx.getEventBus();
        final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
        final URI atomUri1 = ctx.getWonNodeInformationService().generateAtomURI(wonNodeUri);
        final URI atomUri2 = ctx.getWonNodeInformationService().generateAtomURI(wonNodeUri);
        final URI atomUri3 = ctx.getWonNodeInformationService().generateAtomURI(wonNodeUri);
        final URI atomUri4 = ctx.getWonNodeInformationService().generateAtomURI(wonNodeUri);
        final URI atom1GroupSocket = URI.create(atomUri1.toString() + "#groupSocket");
        final BotBehaviour bbCreateAtom1 = new BotBehaviour(ctx, "bbCreateAtom1") {

            @Override
            protected void onActivate(Optional<Object> message) {
                final String atomUriString = atomUri1.toString();
                AtomContent atomContent = AtomContent.builder(atomUri1).addTitle("Group Chat Atom (1/4)").addSocket(Socket.builder(atom1GroupSocket).setSocketDefinition(WXGROUP.GroupSocket.asURI()).build()).addType(URI.create(WON.Atom.getURI())).build();
                Authorization autoConnectGroupSocket = Authorization.builder().setGranteeGranteeWildcard(GranteeWildcard.ANYONE).addGrant(b -> b.addSocket(s -> s.addSocketType(WXGROUP.GroupSocket.asURI()).addOperationsSimpleOperationExpression(OP_AUTO_CONNECT))).build();
                WonMessage createMessage = WonMessageBuilder.createAtom().atom(atomUri1).content().graph(RdfOutput.toGraph(atomContent)).content().aclGraph(won.auth.model.RdfOutput.toGraph(getAnyoneMayConnectAuth())).content().aclGraph(won.auth.model.RdfOutput.toGraph(getAnyoneMayReadAnything())).content().aclGraph(won.auth.model.RdfOutput.toGraph(autoConnectGroupSocket)).build();
                createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
                ctx.getBotContextWrapper().rememberAtomUri(atomUri1);
                EventListener successCallback = event -> {
                    logger.debug("group chat atom created");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Create group chat atom");
                EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(createMessage);
            }
        };
        final BotBehaviour bbCreateAtom2 = new BotBehaviour(ctx, "bbCreateAtom2") {

            @Override
            protected void onActivate(Optional<Object> message) {
                final String atomUriString = atomUri2.toString();
                AtomContent atomContent = AtomContent.builder(atomUri2).addTitle("member atom A (2/4)").addSocket(Socket.builder(atomUriString + "#chatSocket").setSocketDefinition(WXCHAT.ChatSocket.asURI()).build()).addType(URI.create(WON.Atom.getURI())).build();
                WonMessage createMessage = WonMessageBuilder.createAtom().atom(atomUri2).content().graph(RdfOutput.toGraph(atomContent)).content().aclGraph(won.auth.model.RdfOutput.toGraph(getAnyoneMayConnectAuth())).content().aclGraph(won.auth.model.RdfOutput.toGraph(getAnyoneMayReadAnything())).build();
                createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
                ctx.getBotContextWrapper().rememberAtomUri(atomUri2);
                EventListener successCallback = event -> {
                    logger.debug("member atom A created");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Create member atom A");
                EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(createMessage);
            }
        };
        final BotBehaviour bbCreateAtom3 = new BotBehaviour(ctx, "bbCreateAtom3") {

            @Override
            protected void onActivate(Optional<Object> message) {
                final String atomUriString = atomUri3.toString();
                AtomContent atomContent = AtomContent.builder(atomUri3).addTitle("member atom B (3/4)").addSocket(Socket.builder(atomUriString + "#chatSocket").setSocketDefinition(WXCHAT.ChatSocket.asURI()).build()).addType(URI.create(WON.Atom.getURI())).build();
                WonMessage createMessage = WonMessageBuilder.createAtom().atom(atomUri3).content().graph(RdfOutput.toGraph(atomContent)).content().aclGraph(won.auth.model.RdfOutput.toGraph(getAnyoneMayConnectAuth())).content().aclGraph(won.auth.model.RdfOutput.toGraph(getAnyoneMayReadAnything())).build();
                createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
                ctx.getBotContextWrapper().rememberAtomUri(atomUri3);
                EventListener successCallback = event -> {
                    logger.debug("member atom B created");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Creating member atom B");
                EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(createMessage);
            }
        };
        final BotBehaviour bbCreateAtom4 = new BotBehaviour(ctx, "bbCreateAtom4") {

            @Override
            protected void onActivate(Optional<Object> message) {
                final String atomUriString = atomUri4.toString();
                AtomContent atomContent = AtomContent.builder(atomUri4).addTitle("member atom C (4/4)").addSocket(Socket.builder(atomUriString + "#chatSocket").setSocketDefinition(WXCHAT.ChatSocket.asURI()).build()).addType(URI.create(WON.Atom.getURI())).build();
                WonMessage createMessage = WonMessageBuilder.createAtom().atom(atomUri4).content().graph(RdfOutput.toGraph(atomContent)).content().aclGraph(won.auth.model.RdfOutput.toGraph(getAnyoneMayConnectAuth())).content().aclGraph(won.auth.model.RdfOutput.toGraph(getAnyoneMayReadAnything())).build();
                createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
                ctx.getBotContextWrapper().rememberAtomUri(atomUri4);
                EventListener successCallback = event -> {
                    logger.debug("member atom C created");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Creating member atom C");
                EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(createMessage);
            }
        };
        BotBehaviour bbSendConnect21 = new BotBehaviour(ctx, "bbSendConnect21") {

            @Override
            protected void onActivate(Optional<Object> message) {
                WonMessage connectMessage = WonMessageBuilder.connect().sockets().sender(URI.create(atomUri2.toString() + "#chatSocket")).recipient(atom1GroupSocket).direction().fromOwner().build();
                connectMessage = ctx.getWonMessageSender().prepareMessage(connectMessage);
                EventListener successCallback = event -> {
                    logger.debug("member A -> group connection requested");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Requesting connection member A -> group");
                EventBotActionUtils.makeAndSubscribeResponseListener(connectMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(connectMessage);
            }
        };
        BotBehaviour bbSendConnect31 = new BotBehaviour(ctx, "bbSendConnect31") {

            @Override
            protected void onActivate(Optional<Object> message) {
                WonMessage connectMessage = WonMessageBuilder.connect().sockets().sender(URI.create(atomUri3.toString() + "#chatSocket")).recipient(atom1GroupSocket).direction().fromOwner().build();
                connectMessage = ctx.getWonMessageSender().prepareMessage(connectMessage);
                EventListener successCallback = event -> {
                    logger.debug("member B -> group connection requested");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Requesting connection member B -> group");
                EventBotActionUtils.makeAndSubscribeResponseListener(connectMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(connectMessage);
            }
        };
        BotBehaviour bbSendConnect41 = new BotBehaviour(ctx, "bbSendConnect41") {

            @Override
            protected void onActivate(Optional<Object> message) {
                WonMessage connectMessage = WonMessageBuilder.connect().sockets().sender(URI.create(atomUri4.toString() + "#chatSocket")).recipient(atom1GroupSocket).direction().fromOwner().build();
                connectMessage = ctx.getWonMessageSender().prepareMessage(connectMessage);
                EventListener successCallback = event -> {
                    logger.debug("member C -> group connection requested");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Requesting connection member C -> group");
                EventBotActionUtils.makeAndSubscribeResponseListener(connectMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(connectMessage);
            }
        };
        BotBehaviour bbWaitForAutoConnect = new BotBehaviour(ctx) {

            @Override
            protected void onActivate(Optional<Object> message) {
                bus.subscribe(ConnectFromOtherAtomEvent.class, new ActionOnceAfterNEventsListener(ctx, new EventFilter() {

                    @Override
                    public boolean accept(Event event) {
                        boolean waitingForThis = ((ConnectFromOtherAtomEvent) event).getSenderSocket().equals(atom1GroupSocket);
                        return waitingForThis;
                    }
                }, 3, new EventBotAction() {

                    @Override
                    public Runnable getActionTask(Event event, EventListener eventListener) {
                        return () -> deactivate();
                    }
                }));
            }
        };
        BotBehaviour bbSendMsg41 = new BotBehaviour(ctx, "bbSendMsg41") {

            @Override
            protected void onActivate(Optional<Object> message) {
                WonMessage connectMessage = WonMessageBuilder.connectionMessage().sockets().sender(URI.create(atomUri4.toString() + "#chatSocket")).recipient(URI.create(atomUri1.toString() + "#groupSocket")).direction().fromOwner().content().text("Hello, world!").build();
                connectMessage = ctx.getWonMessageSender().prepareMessage(connectMessage);
                EventListener successCallback = event -> {
                    logger.debug("member C -> send message to group");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "sending message member C -> group");
                EventBotActionUtils.makeAndSubscribeResponseListener(connectMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(connectMessage);
            }
        };
        BotBehaviour bbWaitForGroupMessage = new BotBehaviour(ctx) {

            @Override
            protected void onActivate(Optional<Object> message) {
                bus.subscribe(MessageFromOtherAtomEvent.class, new ActionOnceAfterNEventsListener(ctx, new EventFilter() {

                    @Override
                    public boolean accept(Event event) {
                        boolean interestedInThis = ((MessageFromOtherAtomEvent) event).getWonMessage().getSenderSocketURIRequired().equals(atom1GroupSocket);
                        return interestedInThis;
                    }
                }, 2, new EventBotAction() {

                    @Override
                    public Runnable getActionTask(Event event, EventListener eventListener) {
                        return () -> passTest(bus);
                    }
                }));
            }
        };
        BehaviourBarrier barrier = new BehaviourBarrier(ctx);
        barrier.waitFor(bbCreateAtom1, bbCreateAtom2, bbCreateAtom3, bbCreateAtom4);
        barrier.thenStart(bbSendConnect21, bbSendConnect31, bbSendConnect41);
        barrier.activate();
        bbWaitForAutoConnect.onDeactivateActivate(bbSendMsg41);
        bbWaitForGroupMessage.activate();
        bbWaitForAutoConnect.activate();
        bbCreateAtom1.activate();
        bbCreateAtom2.activate();
        bbCreateAtom3.activate();
        bbCreateAtom4.activate();
    });
}
Also used : EventBotAction(won.bot.framework.eventbot.action.EventBotAction) SuccessResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent) LoggerFactory(org.slf4j.LoggerFactory) won.auth.model(won.auth.model) EventBus(won.bot.framework.eventbot.bus.EventBus) CachingLinkedDataSource(won.protocol.util.linkeddata.CachingLinkedDataSource) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ConnectFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherAtomEvent) BehaviourBarrier(won.bot.framework.eventbot.behaviour.BehaviourBarrier) ContentUtils(won.utils.content.ContentUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) WonMessage(won.protocol.message.WonMessage) HashSet(java.util.HashSet) WonMessageBuilder(won.protocol.message.builder.WonMessageBuilder) MessageFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.MessageFromOtherAtomEvent) ActionOnceAfterNEventsListener(won.bot.framework.eventbot.listener.impl.ActionOnceAfterNEventsListener) Shacl2JavaInstanceFactory(won.shacl2java.Shacl2JavaInstanceFactory) Individuals(won.auth.model.Individuals) URI(java.net.URI) Dataset(org.apache.jena.query.Dataset) Socket(won.utils.content.model.Socket) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) BotBehaviour(won.bot.framework.eventbot.behaviour.BotBehaviour) MethodHandles(java.lang.invoke.MethodHandles) RdfOutput(won.utils.content.model.RdfOutput) Set(java.util.Set) Test(org.junit.Test) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) EventBotActionUtils(won.bot.framework.eventbot.action.EventBotActionUtils) LinkedDataFetchingException(won.protocol.rest.LinkedDataFetchingException) AtomContent(won.utils.content.model.AtomContent) AuthEnabledLinkedDataSource(won.auth.linkeddata.AuthEnabledLinkedDataSource) CountDownLatch(java.util.concurrent.CountDownLatch) Event(won.bot.framework.eventbot.event.Event) won.protocol.vocabulary(won.protocol.vocabulary) Optional(java.util.Optional) EventFilter(won.bot.framework.eventbot.filter.EventFilter) EventListener(won.bot.framework.eventbot.listener.EventListener) Assert(org.junit.Assert) GraphFactory(org.apache.jena.sparql.graph.GraphFactory) BotBehaviour(won.bot.framework.eventbot.behaviour.BotBehaviour) ActionOnceAfterNEventsListener(won.bot.framework.eventbot.listener.impl.ActionOnceAfterNEventsListener) MessageFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.MessageFromOtherAtomEvent) Optional(java.util.Optional) BehaviourBarrier(won.bot.framework.eventbot.behaviour.BehaviourBarrier) EventBus(won.bot.framework.eventbot.bus.EventBus) URI(java.net.URI) EventFilter(won.bot.framework.eventbot.filter.EventFilter) WonMessage(won.protocol.message.WonMessage) SuccessResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent) ConnectFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherAtomEvent) MessageFromOtherAtomEvent(won.bot.framework.eventbot.event.impl.wonmessage.MessageFromOtherAtomEvent) Event(won.bot.framework.eventbot.event.Event) EventListener(won.bot.framework.eventbot.listener.EventListener) AtomContent(won.utils.content.model.AtomContent) EventBotAction(won.bot.framework.eventbot.action.EventBotAction) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) Test(org.junit.Test)

Aggregations

URI (java.net.URI)4 ConnectFromOtherAtomEvent (won.bot.framework.eventbot.event.impl.wonmessage.ConnectFromOtherAtomEvent)4 MethodHandles (java.lang.invoke.MethodHandles)3 Optional (java.util.Optional)3 Dataset (org.apache.jena.query.Dataset)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 BaseEventBotAction (won.bot.framework.eventbot.action.BaseEventBotAction)3 EventBotActionUtils (won.bot.framework.eventbot.action.EventBotActionUtils)3 BotBehaviour (won.bot.framework.eventbot.behaviour.BotBehaviour)3 EventBus (won.bot.framework.eventbot.bus.EventBus)3 Event (won.bot.framework.eventbot.event.Event)3 EventListener (won.bot.framework.eventbot.listener.EventListener)3 WonMessage (won.protocol.message.WonMessage)3 WonMessageBuilder (won.protocol.message.builder.WonMessageBuilder)3 HashSet (java.util.HashSet)2 Iterator (java.util.Iterator)2 Set (java.util.Set)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2