Search in sources :

Example 51 with EventListener

use of won.bot.framework.eventbot.listener.EventListener in project webofneeds by researchstudio-sat.

the class AclTests method testSocketCapacity_nonConcurrentAccepts.

@Test(timeout = 60 * 1000)
public void testSocketCapacity_nonConcurrentAccepts() 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 BotBehaviour bbCreateAtom1 = new BotBehaviour(ctx, "bbCreateAtom1") {

            @Override
            protected void onActivate(Optional<Object> message) {
                final String atomUriString = atomUri1.toString();
                AtomContent atomContent = AtomContent.builder(atomUri1).addTitle("Holdable atom (1/3)").addSocket(Socket.builder(atomUriString + "#holdableSocket").setSocketDefinition(WXHOLD.HoldableSocket.asURI()).build()).addType(URI.create(WON.Atom.getURI())).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())).build();
                createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
                ctx.getBotContextWrapper().rememberAtomUri(atomUri1);
                EventListener successCallback = event -> {
                    logger.debug("holdable atom created");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Create holdable 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("holder atom A (2/3)").addSocket(Socket.builder(atomUriString + "#holderSocket").setSocketDefinition(WXHOLD.HolderSocket.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("holder atom A created");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Create holder 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("holder atom B (3/3)").addSocket(Socket.builder(atomUriString + "#holderSocket").setSocketDefinition(WXHOLD.HolderSocket.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("holder atom B created");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Creating holder atom B");
                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() + "#holderSocket")).recipient(URI.create(atomUri1.toString() + "#holdableSocket")).direction().fromOwner().build();
                connectMessage = ctx.getWonMessageSender().prepareMessage(connectMessage);
                EventListener successCallback = event -> {
                    logger.debug("holder A -> holdable connection requested");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Requesting connection holder A -> holdable");
                EventBotActionUtils.makeAndSubscribeResponseListener(connectMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(connectMessage);
            }
        };
        BotBehaviour bbAcceptConnect12 = new BotBehaviour(ctx, "bbAcceptConnect12") {

            @Override
            protected void onActivate(Optional<Object> message) {
                WonMessage connectMessage = WonMessageBuilder.connect().sockets().sender(URI.create(atomUri1.toString() + "#holdableSocket")).recipient(URI.create(atomUri2.toString() + "#holderSocket")).direction().fromOwner().build();
                connectMessage = ctx.getWonMessageSender().prepareMessage(connectMessage);
                EventListener successCallback = event -> {
                    logger.debug("Holder A <-> holdable connection accepted");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Accepting connection holder A <-> holdable");
                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() + "#holderSocket")).recipient(URI.create(atomUri1.toString() + "#holdableSocket")).direction().fromOwner().build();
                connectMessage = ctx.getWonMessageSender().prepareMessage(connectMessage);
                EventListener successCallback = event -> {
                    logger.debug("holder B -> holdable connection requested");
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, "Requesting connection holder B -> holdable");
                EventBotActionUtils.makeAndSubscribeResponseListener(connectMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(connectMessage);
            }
        };
        BotBehaviour bbAcceptConnect13 = new BotBehaviour(ctx, "bbAcceptConnect") {

            @Override
            protected void onActivate(Optional<Object> message) {
                WonMessage connectMessage = WonMessageBuilder.connect().sockets().sender(URI.create(atomUri1.toString() + "#holdableSocket")).recipient(URI.create(atomUri3.toString() + "#holderSocket")).direction().fromOwner().build();
                connectMessage = ctx.getWonMessageSender().prepareMessage(connectMessage);
                EventListener successCallback = event -> {
                    logger.debug("Unexpected: Holder B <-> holdable connection accepted");
                    failTest(bus, String.format("Unexpectedly, holdable %s accepted connection to another holder", atomUri1.toString()));
                };
                EventListener failureCallback = event -> {
                    logger.debug("As expected, accepting second holder conneciton failed");
                    passTest(bus);
                };
                EventBotActionUtils.makeAndSubscribeResponseListener(connectMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(connectMessage);
            }
        };
        BotBehaviour bbPassTest = new BotBehaviour(ctx) {

            @Override
            protected void onActivate(Optional<Object> message) {
                passTest(bus);
            }
        };
        BehaviourBarrier barrier = new BehaviourBarrier(ctx);
        barrier.waitFor(bbCreateAtom1, bbCreateAtom2, bbCreateAtom3);
        barrier.thenStart(bbSendConnect21);
        barrier.activate();
        bbSendConnect21.onDeactivateActivate(bbAcceptConnect12);
        bbAcceptConnect12.onDeactivateActivate(bbSendConnect31);
        bbSendConnect31.onDeactivateActivate(bbAcceptConnect13);
        bbCreateAtom1.activate();
        bbCreateAtom2.activate();
        bbCreateAtom3.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) WonMessage(won.protocol.message.WonMessage) BehaviourBarrier(won.bot.framework.eventbot.behaviour.BehaviourBarrier) EventBus(won.bot.framework.eventbot.bus.EventBus) EventListener(won.bot.framework.eventbot.listener.EventListener) AtomContent(won.utils.content.model.AtomContent) URI(java.net.URI) Test(org.junit.Test)

Example 52 with EventListener

use of won.bot.framework.eventbot.listener.EventListener in project webofneeds by researchstudio-sat.

the class AclTests method testModifyOnBehalf_fail.

@Test(timeout = 60 * 1000)
public void testModifyOnBehalf_fail() throws Exception {
    final AtomicBoolean atom1Created = new AtomicBoolean(false);
    final AtomicBoolean atom2Created = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<URI> createMessageUri1 = new AtomicReference();
    final AtomicReference<URI> createMessageUri2 = new AtomicReference();
    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);
        BotBehaviour bbAtom1 = new BotBehaviour(ctx) {

            @Override
            protected void onActivate(Optional<Object> message) {
                final String atomUriString = atomUri1.toString();
                final AtomContent atomContent = AtomContent.builder(atomUriString).addTitle("Granting 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.addOperationsSimpleOperationExpression(OP_READ)).build();
                WonMessage createMessage = WonMessageBuilder.createAtom().atom(atomUri1).content().graph(RdfOutput.toGraph(atomContent)).content().aclGraph(won.auth.model.RdfOutput.toGraph(auth)).build();
                createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
                ctx.getBotContextWrapper().rememberAtomUri(atomUri1);
                final String action = "Create granting atom";
                EventListener successCallback = event -> {
                    logger.debug("Granting atom created");
                    createMessageUri1.set(((SuccessResponseEvent) event).getOriginalMessageURI());
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, action);
                EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(createMessage);
            }
        };
        BotBehaviour bbAtom2 = new BotBehaviour(ctx) {

            @Override
            protected void onActivate(Optional<Object> message) {
                final String atomUriString = atomUri2.toString();
                final AtomContent atomContent = AtomContent.builder(atomUriString).addTitle("Grantee atom").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(getNobodyMayDoNothing())).build();
                createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
                ctx.getBotContextWrapper().rememberAtomUri(atomUri2);
                final String action = "Create grantee atom";
                EventListener successCallback = event -> {
                    logger.debug("Grantee atom created");
                    createMessageUri2.set(((SuccessResponseEvent) event).getOriginalMessageURI());
                    deactivate();
                };
                EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, action);
                EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
                ctx.getWonMessageSender().sendMessage(createMessage);
            }
        };
        BotBehaviour bbReplaceAtom1FromAtom2 = new BotBehaviour(ctx) {

            @Override
            protected void onActivate(Optional<Object> message) {
                WonMessage replaceMessage = WonMessageBuilder.replace().atom(atomUri1).content().graph(RdfOutput.toGraph(AtomContent.builder().addTitle("Replaced title").addTag("ANewTag").addType(URI.create(WON.Persona.getURI())).addSocket(Socket.builder().setSocketDefinition(WXBUDDY.BuddySocket.asURI()).build()).addSocket(Socket.builder().setSocketDefinition(WXHOLD.HolderSocket.asURI()).build()).build())).build();
                EventListener passIfFailure = event -> {
                    logger.debug("Illegal replace denied successfully");
                    deactivate();
                    passTest(bus);
                };
                replaceMessage = ctx.getWonMessageSender().prepareMessageOnBehalf(replaceMessage, atomUri2);
                EventListener failIfSuccess = makeSuccessCallbackToFailTest(bot, ctx, bus, "modifying atom1 using atom2's WebID");
                EventBotActionUtils.makeAndSubscribeResponseListener(replaceMessage, failIfSuccess, passIfFailure, ctx);
                ctx.getWonMessageSender().sendMessage(replaceMessage);
            }
        };
        BehaviourBarrier barrier = new BehaviourBarrier(ctx);
        barrier.waitFor(bbAtom1, bbAtom2);
        barrier.thenStart(bbReplaceAtom1FromAtom2);
        barrier.activate();
        bbAtom1.activate();
        bbAtom2.activate();
        logger.debug("Finished initializing test 'testQueryBasedMatch()'");
    });
}
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) SuccessResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent) Optional(java.util.Optional) BehaviourBarrier(won.bot.framework.eventbot.behaviour.BehaviourBarrier) AtomicReference(java.util.concurrent.atomic.AtomicReference) EventBus(won.bot.framework.eventbot.bus.EventBus) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WonMessage(won.protocol.message.WonMessage) EventListener(won.bot.framework.eventbot.listener.EventListener) AtomContent(won.utils.content.model.AtomContent) Test(org.junit.Test)

Example 53 with EventListener

use of won.bot.framework.eventbot.listener.EventListener in project webofneeds by researchstudio-sat.

the class SimpleTests method testCreatePersonaWithoutACL.

@Test(timeout = 60 * 1000)
public void testCreatePersonaWithoutACL() throws Exception {
    runTest(ctx -> {
        EventBus bus = ctx.getEventBus();
        final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
        final URI atomUri = ctx.getWonNodeInformationService().generateAtomURI(wonNodeUri);
        final String atomUriString = atomUri.toString();
        final AtomContent atomContent = new AtomContent(atomUriString);
        atomContent.addTitle("Unit Test Atom ");
        final Socket holderSocket = new Socket(atomUriString + "#holderSocket");
        holderSocket.setSocketDefinition(WXHOLD.HolderSocket.asURI());
        final Socket buddySocket = new Socket(atomUriString + "#buddySocket");
        buddySocket.setSocketDefinition(WXBUDDY.BuddySocket.asURI());
        atomContent.addSocket(holderSocket);
        atomContent.addSocket(buddySocket);
        atomContent.addType(URI.create(WON.Persona.getURI()));
        atomContent.addType(URI.create(WON.Atom.getURI()));
        WonMessage createMessage = WonMessageBuilder.createAtom().atom(atomUri).content().graph(RdfOutput.toGraph(atomContent)).build();
        createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
        ctx.getBotContextWrapper().rememberAtomUri(atomUri);
        final String action = "Create Atom action";
        EventListener successCallback = makeSuccessCallbackToPassTest(bot, bus, action);
        EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, action);
        EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
        ctx.getWonMessageSender().sendMessage(createMessage);
    });
}
Also used : WonMessage(won.protocol.message.WonMessage) EventBus(won.bot.framework.eventbot.bus.EventBus) EventListener(won.bot.framework.eventbot.listener.EventListener) AtomContent(won.utils.content.model.AtomContent) URI(java.net.URI) Socket(won.utils.content.model.Socket) Test(org.junit.Test)

Example 54 with EventListener

use of won.bot.framework.eventbot.listener.EventListener in project webofneeds by researchstudio-sat.

the class SimpleTests method testQueryBasedMatch.

@Test(timeout = 60 * 1000)
public void testQueryBasedMatch() throws Exception {
    final AtomicBoolean atom1Created = new AtomicBoolean(false);
    final AtomicBoolean atom2Created = new AtomicBoolean(false);
    runTest(ctx -> {
        EventBus bus = ctx.getEventBus();
        final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
        final URI atomUri1 = ctx.getWonNodeInformationService().generateAtomURI(wonNodeUri);
        {
            final String atomUriString = atomUri1.toString();
            final AtomContent atomContent = new AtomContent(atomUriString);
            atomContent.addTitle("Match target atom");
            atomContent.addTag("tag-to-match");
            final Socket chatSocket = new Socket(atomUriString + "#chatSocket");
            chatSocket.setSocketDefinition(WXCHAT.ChatSocket.asURI());
            atomContent.addSocket(chatSocket);
            atomContent.addType(URI.create(WON.Atom.getURI()));
            WonMessage createMessage = WonMessageBuilder.createAtom().atom(atomUri1).content().graph(RdfOutput.toGraph(atomContent)).build();
            createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
            ctx.getBotContextWrapper().rememberAtomUri(atomUri1);
            final String action = "Create match target atom";
            EventListener successCallback = event -> {
                logger.debug("Match target atom created");
                atom1Created.set(true);
            };
            EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, action);
            EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
            ctx.getWonMessageSender().sendMessage(createMessage);
        }
        // create match source
        final URI atomUri2 = ctx.getWonNodeInformationService().generateAtomURI(wonNodeUri);
        {
            final String atomUriString = atomUri2.toString();
            final AtomContent atomContent = new AtomContent(atomUriString);
            atomContent.addTitle("Match source atom");
            atomContent.addSparqlQuery("PREFIX won:<https://w3id.org/won/core#>\n" + "PREFIX con:<https://w3id.org/won/content#>\n" + "SELECT ?result (1.0 AS ?score) WHERE {" + "?result a won:Atom ;" + "    con:tag \"tag-to-match\"." + "}");
            final Socket chatSocket = new Socket(atomUriString + "#chatSocket");
            chatSocket.setSocketDefinition(WXCHAT.ChatSocket.asURI());
            atomContent.addSocket(chatSocket);
            atomContent.addType(URI.create(WON.Atom.getURI()));
            WonMessage createMessage = WonMessageBuilder.createAtom().atom(atomUri2).content().graph(RdfOutput.toGraph(atomContent)).build();
            createMessage = ctx.getWonMessageSender().prepareMessage(createMessage);
            ctx.getBotContextWrapper().rememberAtomUri(atomUri2);
            final String action = "Create match source atom";
            EventListener successCallback = event -> {
                logger.debug("Match source atom created");
                atom2Created.set(true);
            };
            EventListener failureCallback = makeFailureCallbackToFailTest(bot, ctx, bus, action);
            EventBotActionUtils.makeAndSubscribeResponseListener(createMessage, successCallback, failureCallback, ctx);
            ctx.getWonMessageSender().sendMessage(createMessage);
        }
        // create listener waiting for the hint
        bus.subscribe(HintFromMatcherEvent.class, (Event event) -> ((HintFromMatcherEvent) event).getRecipientAtom().equals(atomUri2) && ((HintFromMatcherEvent) event).getHintTargetAtom().equals(atomUri1), makeAction(ctx, event -> bus.publish(new TestPassedEvent(bot))));
        logger.debug("Finished initializing test 'testQueryBasedMatch()'");
    });
}
Also used : Socket(won.utils.content.model.Socket) Logger(org.slf4j.Logger) WON(won.protocol.vocabulary.WON) TestPassedEvent(won.bot.framework.eventbot.event.impl.test.TestPassedEvent) MethodHandles(java.lang.invoke.MethodHandles) LoggerFactory(org.slf4j.LoggerFactory) WXBUDDY(won.protocol.vocabulary.WXBUDDY) EventBus(won.bot.framework.eventbot.bus.EventBus) RdfOutput(won.utils.content.model.RdfOutput) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) EventBotActionUtils(won.bot.framework.eventbot.action.EventBotActionUtils) AtomContent(won.utils.content.model.AtomContent) HintFromMatcherEvent(won.bot.framework.eventbot.event.impl.wonmessage.HintFromMatcherEvent) WonMessage(won.protocol.message.WonMessage) WonMessageBuilder(won.protocol.message.builder.WonMessageBuilder) WXHOLD(won.protocol.vocabulary.WXHOLD) Event(won.bot.framework.eventbot.event.Event) EventBotActionUtils.makeAction(won.bot.framework.eventbot.action.EventBotActionUtils.makeAction) EventListener(won.bot.framework.eventbot.listener.EventListener) WXCHAT(won.protocol.vocabulary.WXCHAT) URI(java.net.URI) TestPassedEvent(won.bot.framework.eventbot.event.impl.test.TestPassedEvent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) WonMessage(won.protocol.message.WonMessage) TestPassedEvent(won.bot.framework.eventbot.event.impl.test.TestPassedEvent) HintFromMatcherEvent(won.bot.framework.eventbot.event.impl.wonmessage.HintFromMatcherEvent) Event(won.bot.framework.eventbot.event.Event) EventBus(won.bot.framework.eventbot.bus.EventBus) EventListener(won.bot.framework.eventbot.listener.EventListener) AtomContent(won.utils.content.model.AtomContent) URI(java.net.URI) Socket(won.utils.content.model.Socket) Test(org.junit.Test)

Example 55 with EventListener

use of won.bot.framework.eventbot.listener.EventListener in project webofneeds by researchstudio-sat.

the class AbstractBotBasedTest method runTestWithAsserts.

protected void runTestWithAsserts(Consumer<EventListenerContext> botInitializer, Runnable asserter) throws Exception {
    logger.debug("preparing bot test in runTestWithAsserts(..)");
    MutableStringHolder errorMessage = new MutableStringHolder();
    bot.setInitializer(ctx -> {
        bot.newCountDownLatch(1);
        EventBus bus = ctx.getEventBus();
        bus.clear();
        // now, add a listener to the WorkDoneEvent.
        // its only purpose is to trip the CyclicBarrier instance that
        // the test method is waiting on
        bus.subscribe(TestPassedEvent.class, new ActionOnEventListener(ctx, new CountdownLatchAction(ctx, bot.getCountDownLatch())));
        bus.subscribe(TestFailedEvent.class, new ActionOnEventListener(ctx, new MultipleActions(ctx, false, new BaseEventBotAction(ctx) {

            @Override
            protected void doRun(Event event, EventListener executingListener) throws Exception {
                if (event instanceof TestFailedEvent) {
                    errorMessage.set(((TestFailedEvent) event).getMessage());
                    if (errorMessage.isEmpty()) {
                        errorMessage.set("[no error message provided]");
                    }
                }
            }
        }, new CountdownLatchAction(ctx, bot.getCountDownLatch()))));
        // now run test-specific initializer
        if (botInitializer != null) {
            botInitializer.accept(ctx);
        }
    });
    // possibly, the bot is already running (the SpringAwareBotManager finds and
    // initializes it)
    // make sure we can re-initialize it here
    bot.shutdown();
    // re-initialize
    bot.initialize();
    logger.debug("bot re-initialized");
    logger.debug("waiting for test to finish...");
    bot.getCountDownLatch().await();
    if (errorMessage.isPresent()) {
        logger.debug("test failed");
        Assert.fail(errorMessage.get());
    }
    logger.debug("executing asserts (if any)");
    // execute any asserts
    asserter.run();
    logger.debug("test passed");
}
Also used : MultipleActions(won.bot.framework.eventbot.action.impl.MultipleActions) BaseEventBotAction(won.bot.framework.eventbot.action.BaseEventBotAction) TestPassedEvent(won.bot.framework.eventbot.event.impl.test.TestPassedEvent) FailureResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent) DeliveryResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.DeliveryResponseEvent) Event(won.bot.framework.eventbot.event.Event) SuccessResponseEvent(won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent) TestFailedEvent(won.bot.framework.eventbot.event.impl.test.TestFailedEvent) EventBus(won.bot.framework.eventbot.bus.EventBus) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) ActionOnEventListener(won.bot.framework.eventbot.listener.impl.ActionOnEventListener) EventListener(won.bot.framework.eventbot.listener.EventListener) CountdownLatchAction(won.integrationtest.support.CountdownLatchAction) TestFailedEvent(won.bot.framework.eventbot.event.impl.test.TestFailedEvent)

Aggregations

EventListener (won.bot.framework.eventbot.listener.EventListener)57 Event (won.bot.framework.eventbot.event.Event)54 BaseEventBotAction (won.bot.framework.eventbot.action.BaseEventBotAction)41 URI (java.net.URI)37 EventBus (won.bot.framework.eventbot.bus.EventBus)36 Dataset (org.apache.jena.query.Dataset)31 EventListenerContext (won.bot.framework.eventbot.EventListenerContext)31 WonMessage (won.protocol.message.WonMessage)30 ActionOnceAfterNEventsListener (won.bot.framework.eventbot.listener.impl.ActionOnceAfterNEventsListener)24 MethodHandles (java.lang.invoke.MethodHandles)23 Logger (org.slf4j.Logger)23 LoggerFactory (org.slf4j.LoggerFactory)23 EventBotActionUtils (won.bot.framework.eventbot.action.EventBotActionUtils)22 WonMessageBuilder (won.protocol.message.builder.WonMessageBuilder)20 ActionOnEventListener (won.bot.framework.eventbot.listener.impl.ActionOnEventListener)19 BotBehaviour (won.bot.framework.eventbot.behaviour.BotBehaviour)18 SuccessResponseEvent (won.bot.framework.eventbot.event.impl.wonmessage.SuccessResponseEvent)18 Optional (java.util.Optional)17 Test (org.junit.Test)17 EventBotAction (won.bot.framework.eventbot.action.EventBotAction)17