diff --git a/pom.xml b/pom.xml
index 2a9b4d5..0590f31 100644
--- a/pom.xml
+++ b/pom.xml
@@ -39,7 +39,7 @@
at.researchstudio.satwon-bot
- 0.8
+ 0.9-SNAPSHOT
diff --git a/src/main/java/won/bot/debugbot/action/ConnectWithAssociatedAtomAction.java b/src/main/java/won/bot/debugbot/action/ConnectWithAssociatedAtomAction.java
index b129768..ed304da 100644
--- a/src/main/java/won/bot/debugbot/action/ConnectWithAssociatedAtomAction.java
+++ b/src/main/java/won/bot/debugbot/action/ConnectWithAssociatedAtomAction.java
@@ -35,9 +35,8 @@
import won.protocol.util.linkeddata.WonLinkedDataUtils;
/**
- * BaseEventBotAction connecting two atoms on the specified sockets or on two
- * other, compatible sockets. Requires an AtomSpecificEvent to run and expeects
- * the atomURI from the event to be associated with another atom URI via the
+ * BaseEventBotAction connecting two atoms on the specified sockets or on two other, compatible sockets. Requires an
+ * AtomSpecificEvent to run and expeects the atomURI from the event to be associated with another atom URI via the
* botContext.saveToObjectMap method.
*/
public class ConnectWithAssociatedAtomAction extends BaseEventBotAction {
@@ -47,7 +46,7 @@ public class ConnectWithAssociatedAtomAction extends BaseEventBotAction {
private final String welcomeMessage;
public ConnectWithAssociatedAtomAction(final EventListenerContext eventListenerContext, final URI targetSocketType,
- final URI localSocketType, String welcomeMessage) {
+ final URI localSocketType, String welcomeMessage) {
super(eventListenerContext);
Objects.requireNonNull(targetSocketType);
Objects.requireNonNull(localSocketType);
@@ -56,11 +55,6 @@ public ConnectWithAssociatedAtomAction(final EventListenerContext eventListenerC
this.welcomeMessage = welcomeMessage;
}
- public ConnectWithAssociatedAtomAction(EventListenerContext eventListenerContext, String welcomeMessage) {
- super(eventListenerContext);
- this.welcomeMessage = welcomeMessage;
- }
-
@Override
public void doRun(Event event, EventListener executingListener) {
if (!(event instanceof AtomSpecificEvent)) {
@@ -85,39 +79,26 @@ private Optional createWonMessage(URI fromUri, URI toUri) throws Won
LinkedDataSource linkedDataSource = getEventListenerContext().getLinkedDataSource();
if (localSocketType.isPresent() && targetSocketType.isPresent()) {
URI localSocket = localSocketType
- .map(socketType -> WonLinkedDataUtils
- .getSocketsOfType(fromUri, socketType, linkedDataSource)
- .stream().findFirst())
- .orElseThrow(() -> new IllegalStateException("No socket found to connect on " + fromUri))
- .get();
+ .map(socketType -> WonLinkedDataUtils.getSocketsOfType(fromUri, socketType, linkedDataSource)
+ .stream().findFirst())
+ .orElseThrow(() -> new IllegalStateException("No socket found to connect on " + fromUri)).get();
URI targetSocket = targetSocketType
- .map(socketType -> WonLinkedDataUtils.getSocketsOfType(toUri, socketType, linkedDataSource)
- .stream()
- .findFirst())
- .orElseThrow(() -> new IllegalStateException("No socket found to connect on " + fromUri))
- .get();
- return Optional.of(WonMessageBuilder
- .connect()
- .sockets()
- /**/.sender(localSocket)
- /**/.recipient(targetSocket)
- .content().text(welcomeMessage).build());
+ .map(socketType -> WonLinkedDataUtils.getSocketsOfType(toUri, socketType, linkedDataSource).stream()
+ .findFirst())
+ .orElseThrow(() -> new IllegalStateException("No socket found to connect on " + fromUri)).get();
+ return Optional.of(WonMessageBuilder.connect().sockets()/**/.sender(localSocket)/**/.recipient(targetSocket)
+ .content().text(welcomeMessage).build());
}
// no sockets specified or specified sockets not supported. try a random
// compatibly pair
Set> compatibleSockets = WonLinkedDataUtils.getCompatibleSocketsForAtoms(linkedDataSource, fromUri,
- toUri);
+ toUri);
if (!compatibleSockets.isEmpty()) {
List> shuffledSocketPairs = new ArrayList<>(compatibleSockets);
Collections.shuffle(shuffledSocketPairs);
Pair sockets = shuffledSocketPairs.get(0);
- return Optional.of(WonMessageBuilder
- .connect()
- .sockets()
- /**/.sender(sockets.getFirst())
- /**/.recipient(sockets.getSecond())
- .content().text(welcomeMessage)
- .build());
+ return Optional.of(WonMessageBuilder.connect().sockets()/**/.sender(sockets.getFirst())
+ /**/.recipient(sockets.getSecond()).content().text(welcomeMessage).build());
}
return Optional.empty();
}
diff --git a/src/main/java/won/bot/debugbot/action/CreateDebugAtomWithSocketsAction.java b/src/main/java/won/bot/debugbot/action/CreateDebugAtomAction.java
similarity index 81%
rename from src/main/java/won/bot/debugbot/action/CreateDebugAtomWithSocketsAction.java
rename to src/main/java/won/bot/debugbot/action/CreateDebugAtomAction.java
index 4c3ddf1..30f274d 100644
--- a/src/main/java/won/bot/debugbot/action/CreateDebugAtomWithSocketsAction.java
+++ b/src/main/java/won/bot/debugbot/action/CreateDebugAtomAction.java
@@ -1,169 +1,164 @@
-/*
- * Copyright 2012 Research Studios Austria Forschungsges.m.b.H. Licensed under
- * the Apache License, Version 2.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of the License
- * at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
- * law or agreed to in writing, software distributed under the License is
- * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the specific language
- * governing permissions and limitations under the License.
- */
-package won.bot.debugbot.action;
-
-import java.lang.invoke.MethodHandles;
-import java.net.URI;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.jena.query.Dataset;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import won.bot.debugbot.enums.HintType;
-import won.bot.debugbot.event.AtomCreatedEventForDebugConnect;
-import won.bot.debugbot.event.AtomCreatedEventForDebugHint;
-import won.bot.debugbot.event.ConnectDebugCommandEvent;
-import won.bot.debugbot.event.HintDebugCommandEvent;
-import won.bot.framework.eventbot.EventListenerContext;
-import won.bot.framework.eventbot.action.EventBotActionUtils;
-import won.bot.framework.eventbot.action.impl.atomlifecycle.AbstractCreateAtomAction;
-import won.bot.framework.eventbot.action.impl.counter.Counter;
-import won.bot.framework.eventbot.action.impl.counter.CounterImpl;
-import won.bot.framework.eventbot.bus.EventBus;
-import won.bot.framework.eventbot.event.AtomCreationFailedEvent;
-import won.bot.framework.eventbot.event.AtomSpecificEvent;
-import won.bot.framework.eventbot.event.Event;
-import won.bot.framework.eventbot.event.impl.atomlifecycle.AtomCreatedEvent;
-import won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent;
-import won.bot.framework.eventbot.listener.EventListener;
-import won.bot.framework.extensions.matcher.MatcherExtensionAtomCreatedEvent;
-import won.protocol.message.WonMessage;
-import won.protocol.service.WonNodeInformationService;
-import won.protocol.util.DefaultAtomModelWrapper;
-import won.protocol.util.Prefixer;
-import won.protocol.util.RdfUtils;
-import won.protocol.util.WonRdfUtils;
-import won.protocol.vocabulary.WONMATCH;
-
-/**
- * Creates an atom with the specified sockets. If no socket is specified, the
- * chatSocket will be used.
- */
-public class CreateDebugAtomWithSocketsAction extends AbstractCreateAtomAction {
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
- private final Counter counter = new CounterImpl("DebugAtomsCounter");
- private boolean isInitialForHint;
- private boolean isInitialForConnect;
-
- public CreateDebugAtomWithSocketsAction(final EventListenerContext eventListenerContext,
- final boolean usedForTesting, final boolean doNotMatch, final URI... sockets) {
- super(eventListenerContext, eventListenerContext.getBotContextWrapper().getAtomCreateListName(), usedForTesting,
- doNotMatch, sockets);
- }
-
- @Override
- protected void doRun(Event event, EventListener executingListener) throws Exception {
- String replyText;
- URI reactingToAtomUriTmp;
- Dataset atomDataset = null;
- if (event instanceof AtomSpecificEvent) {
- reactingToAtomUriTmp = ((AtomSpecificEvent) event).getAtomURI();
- } else {
- logger.warn("could not process non-atom specific event {}", event);
- return;
- }
- if (event instanceof MatcherExtensionAtomCreatedEvent) {
- atomDataset = ((MatcherExtensionAtomCreatedEvent) event).getAtomData();
- } else if (event instanceof HintDebugCommandEvent) {
- reactingToAtomUriTmp = ((HintDebugCommandEvent) event).getTargetAtomURI();
- } else if (event instanceof ConnectDebugCommandEvent) {
- reactingToAtomUriTmp = ((ConnectDebugCommandEvent) event).getTargetAtomURI();
- } else {
- logger.error("CreateEchoAtomWithSocketsAction cannot handle " + event.getClass().getName());
- return;
- }
- final URI reactingToAtomUri = reactingToAtomUriTmp;
- String titleString = null;
- boolean createAtom = true;
- if (atomDataset != null) {
- DefaultAtomModelWrapper atomModelWrapper = new DefaultAtomModelWrapper(atomDataset);
- titleString = atomModelWrapper.getSomeTitleFromIsOrAll("en", "de");
- createAtom = atomModelWrapper.flag(WONMATCH.UsedForTesting) && !atomModelWrapper.flag(WONMATCH.NoHintForMe);
- }
- if (!createAtom)
- return; // if create atom is false do not continue the debug atom creation
- if (titleString != null) {
- if (isInitialForConnect) {
- replyText = "Debugging with initial connect: " + titleString;
- } else if (isInitialForHint) {
- replyText = "Debugging with initial hint: " + titleString;
- } else {
- replyText = "Debugging: " + titleString;
- }
- } else {
- replyText = "Debug Atom No. " + counter.increment();
- }
- EventListenerContext ctx = getEventListenerContext();
- WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService();
- EventBus bus = ctx.getEventBus();
- final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
- final URI atomURI = wonNodeInformationService.generateAtomURI(wonNodeUri);
- DefaultAtomModelWrapper atomModelWrapper = new DefaultAtomModelWrapper(atomURI);
- atomModelWrapper.setTitle(replyText);
- atomModelWrapper.setDescription("This is an atom automatically created by the DebugBot.");
- atomModelWrapper.setSeeksTitle(replyText);
- atomModelWrapper.setSeeksDescription("This is an atom automatically created by the DebugBot.");
- int i = 1;
- for (URI socket : sockets) {
- atomModelWrapper.addSocket(atomURI + "#socket" + i, socket.toString());
- i++;
- }
- final Dataset debugAtomDataset = atomModelWrapper.copyDatasetWithoutSysinfo();
- final Event origEvent = event;
- logger.debug("creating atom on won node {} with content {} ", wonNodeUri,
- StringUtils.abbreviate(RdfUtils.toString(Prefixer.setPrefixes(debugAtomDataset)), 150));
- WonMessage createAtomMessage = createWonMessage(atomURI, wonNodeUri, debugAtomDataset);
- createAtomMessage = getEventListenerContext().getWonMessageSender().prepareMessage(createAtomMessage);
- // remember the atom URI so we can react to success/failure responses
- EventBotActionUtils.rememberInList(ctx, atomURI, uriListName);
- EventListener successCallback = event12 -> {
- logger.debug("atom creation successful, new atom URI is {}", atomURI);
- // save the mapping between the original and the reaction in to the context.
- getEventListenerContext().getBotContextWrapper().addUriAssociation(reactingToAtomUri, atomURI);
- if (origEvent instanceof HintDebugCommandEvent || isInitialForHint) {
- HintType hintType = HintType.RANDOM_SOCKET_HINT; // default: hint to random compatible sockets
- if (origEvent instanceof HintDebugCommandEvent) {
- hintType = ((HintDebugCommandEvent) origEvent).getHintType();
- bus.publish(new AtomCreatedEventForDebugHint(origEvent, atomURI, wonNodeUri, debugAtomDataset,
- hintType));
- } else {
- bus.publish(new AtomCreatedEventForDebugHint(origEvent, atomURI, wonNodeUri, debugAtomDataset,
- hintType));
- }
- } else if ((origEvent instanceof ConnectDebugCommandEvent) || isInitialForConnect) {
- bus.publish(new AtomCreatedEventForDebugConnect(atomURI, wonNodeUri, debugAtomDataset, null));
- } else {
- bus.publish(new AtomCreatedEvent(atomURI, wonNodeUri, debugAtomDataset, null));
- }
- };
- EventListener failureCallback = event1 -> {
- String textMessage = WonRdfUtils.MessageUtils
- .getTextMessage(((FailureResponseEvent) event1).getFailureMessage());
- logger.debug("atom creation failed for atom URI {}, original message URI {}: {}", atomURI,
- ((FailureResponseEvent) event1).getOriginalMessageURI(), textMessage);
- EventBotActionUtils.removeFromList(ctx, atomURI, uriListName);
- bus.publish(new AtomCreationFailedEvent(wonNodeUri));
- };
- EventBotActionUtils.makeAndSubscribeResponseListener(createAtomMessage, successCallback, failureCallback, ctx);
- logger.debug("registered listeners for response to message URI {}", createAtomMessage.getMessageURI());
- ctx.getWonMessageSender().sendMessage(createAtomMessage);
- logger.debug("atom creation message sent with message URI {}", createAtomMessage.getMessageURI());
- }
-
- public void setIsInitialForHint(final boolean isInitialForHint) {
- this.isInitialForHint = isInitialForHint;
- }
-
- public void setIsInitialForConnect(final boolean isInitialForConnect) {
- this.isInitialForConnect = isInitialForConnect;
- }
-}
+/*
+ * Copyright 2012 Research Studios Austria Forschungsges.m.b.H. Licensed under
+ * the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License
+ * at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
+ * law or agreed to in writing, software distributed under the License is
+ * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language
+ * governing permissions and limitations under the License.
+ */
+package won.bot.debugbot.action;
+
+import java.lang.invoke.MethodHandles;
+import java.net.URI;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.jena.query.Dataset;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import won.bot.debugbot.enums.HintType;
+import won.bot.debugbot.event.AtomCreatedEventForDebugConnect;
+import won.bot.debugbot.event.AtomCreatedEventForDebugHint;
+import won.bot.debugbot.event.ConnectDebugCommandEvent;
+import won.bot.debugbot.event.HintDebugCommandEvent;
+import won.bot.framework.eventbot.EventListenerContext;
+import won.bot.framework.eventbot.action.EventBotActionUtils;
+import won.bot.framework.eventbot.action.impl.atomlifecycle.AbstractCreateAtomAction;
+import won.bot.framework.eventbot.action.impl.counter.Counter;
+import won.bot.framework.eventbot.action.impl.counter.CounterImpl;
+import won.bot.framework.eventbot.bus.EventBus;
+import won.bot.framework.eventbot.event.AtomCreationFailedEvent;
+import won.bot.framework.eventbot.event.AtomSpecificEvent;
+import won.bot.framework.eventbot.event.Event;
+import won.bot.framework.eventbot.event.impl.atomlifecycle.AtomCreatedEvent;
+import won.bot.framework.eventbot.event.impl.wonmessage.FailureResponseEvent;
+import won.bot.framework.eventbot.listener.EventListener;
+import won.bot.framework.extensions.matcher.MatcherExtensionAtomCreatedEvent;
+import won.protocol.message.WonMessage;
+import won.protocol.model.SocketType;
+import won.protocol.service.WonNodeInformationService;
+import won.protocol.util.DefaultAtomModelWrapper;
+import won.protocol.util.Prefixer;
+import won.protocol.util.RdfUtils;
+import won.protocol.util.WonRdfUtils;
+import won.protocol.vocabulary.WONMATCH;
+
+/**
+ * Creates an atom with the specified Chat, Buddy and Holdable Sockets. If no socket is specified, the chatSocket will
+ * be used.
+ */
+public class CreateDebugAtomAction extends AbstractCreateAtomAction {
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ private final Counter counter = new CounterImpl("DebugAtomsCounter");
+ private boolean isInitialForHint;
+ private boolean isInitialForConnect;
+
+ public CreateDebugAtomAction(final EventListenerContext eventListenerContext) {
+ super(eventListenerContext);
+ }
+
+ @Override
+ protected void doRun(Event event, EventListener executingListener) throws Exception {
+ String replyText;
+ URI reactingToAtomUriTmp;
+ Dataset atomDataset = null;
+ if (event instanceof AtomSpecificEvent) {
+ reactingToAtomUriTmp = ((AtomSpecificEvent) event).getAtomURI();
+ } else {
+ logger.warn("could not process non-atom specific event {}", event);
+ return;
+ }
+ if (event instanceof MatcherExtensionAtomCreatedEvent) {
+ atomDataset = ((MatcherExtensionAtomCreatedEvent) event).getAtomData();
+ } else if (event instanceof HintDebugCommandEvent) {
+ reactingToAtomUriTmp = ((HintDebugCommandEvent) event).getTargetAtomURI();
+ } else if (event instanceof ConnectDebugCommandEvent) {
+ reactingToAtomUriTmp = ((ConnectDebugCommandEvent) event).getTargetAtomURI();
+ } else {
+ logger.error("CreateEchoAtomWithSocketsAction cannot handle " + event.getClass().getName());
+ return;
+ }
+ final URI reactingToAtomUri = reactingToAtomUriTmp;
+ String titleString = null;
+ boolean createAtom = true;
+ if (atomDataset != null) {
+ DefaultAtomModelWrapper atomModelWrapper = new DefaultAtomModelWrapper(atomDataset);
+ titleString = atomModelWrapper.getSomeTitleFromIsOrAll("en", "de");
+ createAtom = atomModelWrapper.flag(WONMATCH.UsedForTesting) && !atomModelWrapper.flag(WONMATCH.NoHintForMe);
+ }
+ if (!createAtom)
+ return; // if create atom is false do not continue the debug atom creation
+ if (titleString != null) {
+ if (isInitialForConnect) {
+ replyText = "Debugging with initial connect: " + titleString;
+ } else if (isInitialForHint) {
+ replyText = "Debugging with initial hint: " + titleString;
+ } else {
+ replyText = "Debugging: " + titleString;
+ }
+ } else {
+ replyText = "Debug Atom No. " + counter.increment();
+ }
+ EventListenerContext ctx = getEventListenerContext();
+ WonNodeInformationService wonNodeInformationService = ctx.getWonNodeInformationService();
+ EventBus bus = ctx.getEventBus();
+ final URI wonNodeUri = ctx.getNodeURISource().getNodeURI();
+ final URI atomURI = wonNodeInformationService.generateAtomURI(wonNodeUri);
+ DefaultAtomModelWrapper atomModelWrapper = new DefaultAtomModelWrapper(atomURI);
+ atomModelWrapper.setTitle(replyText);
+ atomModelWrapper.setDescription("This is an atom automatically created by the DebugBot.");
+ atomModelWrapper.setSeeksTitle(replyText);
+ atomModelWrapper.setSeeksDescription("This is an atom automatically created by the DebugBot.");
+ atomModelWrapper.addSocket(atomURI + "#chatSocket", SocketType.ChatSocket.getURI().toString());
+ atomModelWrapper.addSocket(atomURI + "#holdableSocket", SocketType.HoldableSocket.getURI().toString());
+ atomModelWrapper.addSocket(atomURI + "#buddySocket", SocketType.BuddySocket.getURI().toString());
+
+ final Dataset debugAtomDataset = atomModelWrapper.copyDatasetWithoutSysinfo();
+ final Event origEvent = event;
+ logger.debug("creating atom on won node {} with content {} ", wonNodeUri,
+ StringUtils.abbreviate(RdfUtils.toString(Prefixer.setPrefixes(debugAtomDataset)), 150));
+ WonMessage createAtomMessage = createWonMessage(atomURI, debugAtomDataset);
+ createAtomMessage = getEventListenerContext().getWonMessageSender().prepareMessage(createAtomMessage);
+ // remember the atom URI so we can react to success/failure responses
+ ctx.getBotContextWrapper().rememberAtomUri(atomURI);
+ EventListener successCallback = event12 -> {
+ logger.debug("atom creation successful, new atom URI is {}", atomURI);
+ // save the mapping between the original and the reaction in to the context.
+ getEventListenerContext().getBotContextWrapper().addUriAssociation(reactingToAtomUri, atomURI);
+ if (origEvent instanceof HintDebugCommandEvent || isInitialForHint) {
+ HintType hintType = HintType.RANDOM_SOCKET_HINT; // default: hint to random compatible sockets
+ if (origEvent instanceof HintDebugCommandEvent) {
+ hintType = ((HintDebugCommandEvent) origEvent).getHintType();
+ }
+ bus.publish(
+ new AtomCreatedEventForDebugHint(origEvent, atomURI, wonNodeUri, debugAtomDataset, hintType));
+ } else if ((origEvent instanceof ConnectDebugCommandEvent) || isInitialForConnect) {
+ bus.publish(new AtomCreatedEventForDebugConnect(atomURI, wonNodeUri, debugAtomDataset, null));
+ } else {
+ bus.publish(new AtomCreatedEvent(atomURI, wonNodeUri, debugAtomDataset, null));
+ }
+ };
+ EventListener failureCallback = event1 -> {
+ String textMessage = WonRdfUtils.MessageUtils
+ .getTextMessage(((FailureResponseEvent) event1).getFailureMessage());
+ logger.debug("atom creation failed for atom URI {}, original message URI {}: {}", atomURI,
+ ((FailureResponseEvent) event1).getOriginalMessageURI(), textMessage);
+ ctx.getBotContextWrapper().removeAtomUri(atomURI);
+ bus.publish(new AtomCreationFailedEvent(wonNodeUri));
+ };
+ EventBotActionUtils.makeAndSubscribeResponseListener(createAtomMessage, successCallback, failureCallback, ctx);
+ logger.debug("registered listeners for response to message URI {}", createAtomMessage.getMessageURI());
+ ctx.getWonMessageSender().sendMessage(createAtomMessage);
+ logger.debug("atom creation message sent with message URI {}", createAtomMessage.getMessageURI());
+ }
+
+ public void setIsInitialForHint(final boolean isInitialForHint) {
+ this.isInitialForHint = isInitialForHint;
+ }
+
+ public void setIsInitialForConnect(final boolean isInitialForConnect) {
+ this.isInitialForConnect = isInitialForConnect;
+ }
+}
diff --git a/src/main/java/won/bot/debugbot/action/HintAssociatedAtomAction.java b/src/main/java/won/bot/debugbot/action/HintAssociatedAtomAction.java
index 34b558c..eab16c5 100644
--- a/src/main/java/won/bot/debugbot/action/HintAssociatedAtomAction.java
+++ b/src/main/java/won/bot/debugbot/action/HintAssociatedAtomAction.java
@@ -38,25 +38,19 @@
import won.protocol.util.linkeddata.WonLinkedDataUtils;
/**
- * BaseEventBotAction connecting two atoms on the specified sockets, or on other
- * compatible sockets, if the Event default sockets if none are specified.
- * Requires an AtomSpecificEvent to run and expects the atomURI from the event
- * to be associated with another atom URI via the botContext.saveToObjectMap
- * method. If the event is a AtomCreatedEventForDebugHint the HintType is
- * extracted from it, otherwise HintType.ATOM_HINT is assumed. If the event is a
- * AtomCreatedEventForDebugHint we send a text message explaining what kind of
- * hint we produced.
+ * BaseEventBotAction connecting two atoms on the specified sockets, or on other compatible sockets, if the Event
+ * default sockets if none are specified. Requires an AtomSpecificEvent to run and expects the atomURI from the event to
+ * be associated with another atom URI via the botContext.saveToObjectMap method. If the event is a
+ * AtomCreatedEventForDebugHint the HintType is extracted from it, otherwise HintType.ATOM_HINT is assumed. If the event
+ * is a AtomCreatedEventForDebugHint we send a text message explaining what kind of hint we produced.
*
*
If it is HintType.ATOM_HINT, an AtomHintMessage is sent.
- *
if it is HintType.SOCKET_HINT, the specified sockets are used (i.e.
- * local/targetSocketType). If those are not specified, RANDOM_SOCKET_HINT is
- * assumed
- *
if it is HintType.RANDOM_SOCKET_HINT, the two compatible sockets are
- * selected at random for the hint. If there are no compatible sockets,
- * INCOMPATIBLE_SOCKET_HINT is assumed
- *
if it is HintType.INCOMPATIBLE_SOCKET_HINT, a random pair of sockets is
- * selected that is incompatible. If we don't find one, we log an error
- * message.
+ *
if it is HintType.SOCKET_HINT, the specified sockets are used (i.e. local/targetSocketType). If those are not
+ * specified, RANDOM_SOCKET_HINT is assumed
+ *
if it is HintType.RANDOM_SOCKET_HINT, the two compatible sockets are selected at random for the hint. If there
+ * are no compatible sockets, INCOMPATIBLE_SOCKET_HINT is assumed
+ *
if it is HintType.INCOMPATIBLE_SOCKET_HINT, a random pair of sockets is selected that is incompatible. If we
+ * don't find one, we log an error message.
*
*
*/
@@ -67,22 +61,13 @@ public class HintAssociatedAtomAction extends BaseEventBotAction {
private final URI matcherURI;
public HintAssociatedAtomAction(final EventListenerContext eventListenerContext, final URI targetSocketType,
- final URI localSocketType, final URI matcherURI) {
+ final URI localSocketType, final URI matcherURI) {
super(eventListenerContext);
this.targetSocketType = Optional.of(targetSocketType);
this.localSocketType = Optional.of(localSocketType);
this.matcherURI = matcherURI;
}
- /**
- * @param eventListenerContext
- * @param matcherURI
- */
- public HintAssociatedAtomAction(EventListenerContext eventListenerContext, URI matcherURI) {
- super(eventListenerContext);
- this.matcherURI = matcherURI;
- }
-
@Override
public void doRun(Event event, EventListener executingListener) {
if (!(event instanceof AtomSpecificEvent)) {
@@ -90,22 +75,20 @@ public void doRun(Event event, EventListener executingListener) {
return;
}
HintType hintType = event instanceof AtomCreatedEventForDebugHint
- ? ((AtomCreatedEventForDebugHint) event).getHintType()
- : HintType.ATOM_HINT;
+ ? ((AtomCreatedEventForDebugHint) event).getHintType() : HintType.ATOM_HINT;
final URI hintTargetAtomUri = ((AtomSpecificEvent) event).getAtomURI();
final URI hintRecipientAtomUri = getEventListenerContext().getBotContextWrapper()
- .getUriAssociation(hintTargetAtomUri);
+ .getUriAssociation(hintTargetAtomUri);
try {
logger.info("Sending hint for {} and {}", hintTargetAtomUri, hintRecipientAtomUri);
- Optional msg = createWonMessage(hintRecipientAtomUri, hintTargetAtomUri, 0.9, matcherURI,
- hintType, event);
+ Optional msg = createWonMessage(hintRecipientAtomUri, hintTargetAtomUri, 0.9, hintType, event);
if (msg.isPresent()) {
logger.debug("Sending Hint message: " + msg.get().toStringForDebug(true));
getEventListenerContext().getMatcherProtocolAtomServiceClient().hint(hintRecipientAtomUri,
- hintTargetAtomUri, 0.9, matcherURI, null, msg.get());
+ hintTargetAtomUri, 0.9, matcherURI, null, msg.get());
} else {
logger.warn("could not send hint for " + hintTargetAtomUri + " to " + hintRecipientAtomUri
- + ": message generation failed ");
+ + ": message generation failed ");
}
} catch (Exception e) {
logger.warn("could not send hint for " + hintTargetAtomUri + " to " + hintRecipientAtomUri, e);
@@ -113,65 +96,49 @@ public void doRun(Event event, EventListener executingListener) {
}
private Optional createWonMessage(URI hintRecipientAtomURI, URI hintTargetAtomURI, double score,
- URI originator, HintType hintType, Event event) throws WonMessageBuilderException {
+ HintType hintType, Event event) throws WonMessageBuilderException {
LinkedDataSource linkedDataSource = getEventListenerContext().getLinkedDataSource();
if (hintType == HintType.ATOM_HINT) {
sendMessageIfReactingToDebugCommand(event,
- "Sending AtomHintMessage to " + hintRecipientAtomURI + " with target " + hintTargetAtomURI
- + ".");
- return Optional.of(WonMessageBuilder
- .atomHint()
- .atom(hintRecipientAtomURI)
- .hintTargetAtom(hintTargetAtomURI)
- .hintScore(score)
- .direction().fromExternal()
- .build());
+ "Sending AtomHintMessage to " + hintRecipientAtomURI + " with target " + hintTargetAtomURI + ".");
+ return Optional.of(WonMessageBuilder.atomHint().atom(hintRecipientAtomURI).hintTargetAtom(hintTargetAtomURI)
+ .hintScore(score).direction().fromExternal().build());
}
if (hintType == HintType.SOCKET_HINT) {
if (localSocketType.isPresent() && targetSocketType.isPresent()) {
Optional hintRecipientSocket = localSocketType.map(socketType -> WonLinkedDataUtils
- .getSocketsOfType(hintRecipientAtomURI, socketType, linkedDataSource).stream()
- .findFirst()
- .orElse(null));
+ .getSocketsOfType(hintRecipientAtomURI, socketType, linkedDataSource).stream().findFirst()
+ .orElse(null));
Optional targetSocket = targetSocketType.map(socketType -> WonLinkedDataUtils
- .getSocketsOfType(hintTargetAtomURI, socketType, linkedDataSource).stream().findFirst()
- .orElse(null));
+ .getSocketsOfType(hintTargetAtomURI, socketType, linkedDataSource).stream().findFirst()
+ .orElse(null));
if (hintRecipientSocket.isPresent() && targetSocket.isPresent()) {
sendMessageIfReactingToDebugCommand(event, "Sending SocketHintMessage to "
- + hintRecipientSocket.get() + " with target " + targetSocket.get() + ".");
- return Optional.of(WonMessageBuilder
- .socketHint()
- .recipientSocket(hintRecipientSocket.get())
- .hintTargetSocket(targetSocket.get())
- .hintScore(score)
- .direction().fromExternal()
- .build());
+ + hintRecipientSocket.get() + " with target " + targetSocket.get() + ".");
+ return Optional.of(WonMessageBuilder.socketHint().recipientSocket(hintRecipientSocket.get())
+ .hintTargetSocket(targetSocket.get()).hintScore(score).direction().fromExternal().build());
} else {
sendMessageIfReactingToDebugCommand(event,
- "Default sockets are specified but not supported by the atoms. Falling back to a random compatible socket combination");
+ "Default sockets are specified but not supported by the atoms. Falling back to a random compatible socket combination");
hintType = HintType.RANDOM_SOCKET_HINT;
}
} else {
sendMessageIfReactingToDebugCommand(event,
- "No default sockets specified, trying random compatible sockets");
+ "No default sockets specified, trying random compatible sockets");
hintType = HintType.RANDOM_SOCKET_HINT;
}
}
if (hintType == HintType.RANDOM_SOCKET_HINT) {
Set> compatibleSockets = WonLinkedDataUtils.getCompatibleSocketsForAtoms(linkedDataSource,
- hintRecipientAtomURI, hintTargetAtomURI);
+ hintRecipientAtomURI, hintTargetAtomURI);
if (!compatibleSockets.isEmpty()) {
List> shuffledSocketPairs = new ArrayList<>(compatibleSockets);
Collections.shuffle(shuffledSocketPairs);
Pair sockets = shuffledSocketPairs.get(0);
sendMessageIfReactingToDebugCommand(event, "Sending SocketHintMessage to " + sockets.getFirst()
- + " with target " + sockets.getSecond() + ".");
- return Optional.of(WonMessageBuilder
- .socketHint()
- .recipientSocket(sockets.getFirst())
- .hintTargetSocket(sockets.getSecond())
- .hintScore(score)
- .build());
+ + " with target " + sockets.getSecond() + ".");
+ return Optional.of(WonMessageBuilder.socketHint().recipientSocket(sockets.getFirst())
+ .hintTargetSocket(sockets.getSecond()).hintScore(score).build());
} else {
sendMessageIfReactingToDebugCommand(event, "No compatible sockets found, trying incompatible sockets");
hintType = HintType.INCOMPATIBLE_SOCKET_HINT;
@@ -179,32 +146,28 @@ private Optional createWonMessage(URI hintRecipientAtomURI, URI hint
}
if (hintType == HintType.INCOMPATIBLE_SOCKET_HINT) {
Set> incompatibleSockets = WonLinkedDataUtils.getIncompatibleSocketsForAtoms(linkedDataSource,
- hintRecipientAtomURI, hintTargetAtomURI);
+ hintRecipientAtomURI, hintTargetAtomURI);
if (!incompatibleSockets.isEmpty()) {
List> shuffledSocketPairs = new ArrayList<>(incompatibleSockets);
Collections.shuffle(shuffledSocketPairs);
Pair sockets = shuffledSocketPairs.get(0);
sendMessageIfReactingToDebugCommand(event, "Sending SocketHintMessage to " + sockets.getFirst()
- + " with target " + sockets.getSecond() + ".");
- return Optional.of(WonMessageBuilder
- .socketHint()
- .recipientSocket(sockets.getFirst())
- .hintTargetSocket(sockets.getSecond())
- .hintScore(score)
- .build());
+ + " with target " + sockets.getSecond() + ".");
+ return Optional.of(WonMessageBuilder.socketHint().recipientSocket(sockets.getFirst())
+ .hintTargetSocket(sockets.getSecond()).hintScore(score).build());
} else {
sendMessageIfReactingToDebugCommand(event,
- "No incompatible compatible sockets found. Not sending any hint.");
+ "No incompatible compatible sockets found. Not sending any hint.");
}
}
logger.info("could not send hint from {} to {}. No suitable sockets found.", hintRecipientAtomURI,
- hintTargetAtomURI);
+ hintTargetAtomURI);
return Optional.empty();
}
private void sendMessageIfReactingToDebugCommand(Event event, String message) {
if (event instanceof AtomCreatedEventForDebugHint
- && ((AtomCreatedEventForDebugHint) event).getCause() instanceof HintDebugCommandEvent) {
+ && ((AtomCreatedEventForDebugHint) event).getCause() instanceof HintDebugCommandEvent) {
AtomCreatedEventForDebugHint e = (AtomCreatedEventForDebugHint) event;
HintDebugCommandEvent cause = (HintDebugCommandEvent) e.getCause();
getEventListenerContext().getEventBus().publish(new ConnectionMessageCommandEvent(cause.getCon(), message));
diff --git a/src/main/java/won/bot/debugbot/action/MessageTimingManager.java b/src/main/java/won/bot/debugbot/action/MessageTimingManager.java
index cc71485..032621d 100644
--- a/src/main/java/won/bot/debugbot/action/MessageTimingManager.java
+++ b/src/main/java/won/bot/debugbot/action/MessageTimingManager.java
@@ -38,14 +38,6 @@ public enum InactivityPeriod {
private final long timeout;
private final long minimalPauseBetweenMessages;
- public long getTimeout() {
- return timeout;
- }
-
- public long getMinimalPauseBetweenMessages() {
- return minimalPauseBetweenMessages;
- }
-
public boolean isWithin(long inactivityInMillis) {
return inactivityInMillis <= timeout;
}
@@ -91,12 +83,6 @@ public InactivityPeriod getInactivityPeriodOfPartner(URI connectionUri) {
return InactivityPeriod.getInactivityPeriod(lastIn);
}
- public InactivityPeriod getInactivityPeriodOfSelf(URI connectionUri) {
- Date lastOut = (Date) context.getBotContext().loadFromObjectMap(KEY_LAST_MESSAGE_OUT_TIMESTAMPS,
- connectionUri.toString());
- return InactivityPeriod.getInactivityPeriod(lastOut);
- }
-
public void updateMessageTimeForMessageSent(URI connectionUri) {
context.getBotContext().saveToObjectMap(KEY_LAST_MESSAGE_OUT_TIMESTAMPS, connectionUri.toString(), new Date());
}
diff --git a/src/main/java/won/bot/debugbot/action/OpenConnectionDebugAction.java b/src/main/java/won/bot/debugbot/action/OpenConnectionDebugAction.java
index 0dd07d3..468ecca 100644
--- a/src/main/java/won/bot/debugbot/action/OpenConnectionDebugAction.java
+++ b/src/main/java/won/bot/debugbot/action/OpenConnectionDebugAction.java
@@ -48,7 +48,7 @@ public class OpenConnectionDebugAction extends BaseEventBotAction {
private final String welcomeHelpMessage;
public OpenConnectionDebugAction(final EventListenerContext context, final String welcomeMessage,
- final String welcomeHelpMessage) {
+ final String welcomeHelpMessage) {
super(context);
this.welcomeMessage = welcomeMessage;
this.welcomeHelpMessage = welcomeHelpMessage;
@@ -59,79 +59,70 @@ public void doRun(final Event event, EventListener executingListener) throws Exc
if (!(event instanceof ConnectFromOtherAtomEvent)) {
return;
}
- if (event instanceof WonMessageReceivedOnConnectionEvent) {
- WonMessageReceivedOnConnectionEvent specificEvent = (WonMessageReceivedOnConnectionEvent) event;
- WonMessage msg = ((WonMessageReceivedOnConnectionEvent) event).getWonMessage();
- WonMessageReceivedOnConnectionEvent msgInConEv = (WonMessageReceivedOnConnectionEvent) event;
- 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));
+
+ WonMessageReceivedOnConnectionEvent specificEvent = (WonMessageReceivedOnConnectionEvent) event;
+ WonMessage msg = ((WonMessageReceivedOnConnectionEvent) event).getWonMessage();
+ WonMessageReceivedOnConnectionEvent msgInConEv = (WonMessageReceivedOnConnectionEvent) event;
+ 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();
+ Optional con = WonLinkedDataUtils.getConnectionForConnectionURI(connectionUri,
+ getEventListenerContext().getLinkedDataSource());
+ String finalWelcomeMessage;
+ if (con.isPresent() && con.get().getState() == ConnectionState.CONNECTED) {
+ finalWelcomeMessage = "Nice, we are connected!";
+ getEventListenerContext().getWonMessageSender()
+ .prepareAndSendMessage(WonMessageBuilder.connectionMessage().sockets()
+ .sender(specificEvent.getSocketURI()).recipient(specificEvent.getTargetSocketURI())
+ .content().text(finalWelcomeMessage).build());
+ } else {
+ if (wait || deny) {
+ finalWelcomeMessage = welcomeMessage + " " + (deny ? "Denying" : "Accepting") + " your request "
+ + (wait ? " after a timeout of " + waitSeconds + " seconds" : "");
+ } else {
+ finalWelcomeMessage = welcomeMessage + " " + welcomeHelpMessage;
}
- 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();
- Optional con = WonLinkedDataUtils.getConnectionForConnectionURI(connectionUri,
- getEventListenerContext().getLinkedDataSource());
- String finalWelcomeMessage;
- if (con.isPresent() && con.get().getState() == ConnectionState.CONNECTED) {
- finalWelcomeMessage = "Nice, we are connected!";
- getEventListenerContext().getWonMessageSender().prepareAndSendMessage(WonMessageBuilder
- .connectionMessage()
- .sockets().sender(specificEvent.getSocketURI())
- .recipient(specificEvent.getTargetSocketURI())
- .content().text(finalWelcomeMessage)
- .build());
+ final WonMessage toSend = deny ? createCloseWonMessage(connectionUri, finalWelcomeMessage)
+ : createConnectWonMessage(msgInConEv, finalWelcomeMessage);
+ Runnable task = () -> getEventListenerContext().getWonMessageSender().prepareAndSendMessage(toSend);
+ if (wait) {
+ Date when = new Date(System.currentTimeMillis() + waitSeconds * 1000);
+ getEventListenerContext().getTaskScheduler().schedule(task, when);
} else {
- 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)
- : createConnectWonMessage(connectionUri, msgInConEv, finalWelcomeMessage);
- Runnable task = () -> getEventListenerContext().getWonMessageSender().prepareAndSendMessage(toSend);
- if (wait) {
- Date when = new Date(System.currentTimeMillis() + waitSeconds * 1000);
- getEventListenerContext().getTaskScheduler().schedule(task, when);
- } else {
- task.run();
- }
+ task.run();
}
}
}
- private WonMessage createConnectWonMessage(URI connectionURI, WonMessageReceivedOnConnectionEvent msgInCon,
- String message) throws WonMessageBuilderException {
- return WonMessageBuilder
- .connect()
- .sockets().sender(msgInCon.getSocketURI()).recipient(msgInCon.getTargetSocketURI())
- .content().text(message)
- .build();
+ private WonMessage createConnectWonMessage(WonMessageReceivedOnConnectionEvent msgInCon, String message)
+ throws WonMessageBuilderException {
+ return WonMessageBuilder.connect().sockets().sender(msgInCon.getSocketURI())
+ .recipient(msgInCon.getTargetSocketURI()).content().text(message).build();
}
private WonMessage createCloseWonMessage(URI connectionURI, String message) throws WonMessageBuilderException {
Dataset connectionRDF = getEventListenerContext().getLinkedDataSource().getDataForResource(connectionURI);
URI targetSocket = WonRdfUtils.ConnectionUtils.getTargetSocketURIFromConnection(connectionRDF, connectionURI);
URI socket = WonRdfUtils.ConnectionUtils.getSocketURIFromConnection(connectionRDF, connectionURI);
- return WonMessageBuilder
- .close()
- .sockets().sender(socket).recipient(targetSocket)
- .content().text(message)
- .build();
+ return WonMessageBuilder.close().sockets().sender(socket).recipient(targetSocket).content().text(message)
+ .build();
}
}
diff --git a/src/main/java/won/bot/debugbot/action/SendChattyMessageAction.java b/src/main/java/won/bot/debugbot/action/SendChattyMessageAction.java
index 5c7a6e6..ce3c32b 100644
--- a/src/main/java/won/bot/debugbot/action/SendChattyMessageAction.java
+++ b/src/main/java/won/bot/debugbot/action/SendChattyMessageAction.java
@@ -58,8 +58,7 @@ protected void doRun(final Event event, EventListener executingListener) throws
Set toRemove = null;
Collection