Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Migrated more controller tests

Christian Bauer04c678a4a94d
diff --git a/controller/src/main/java/org/openremote/controller/command/ExecutableCommand.java b/controller/src/main/java/org/openremote/controller/command/ExecutableCommand.java
index 8c5058425..11a379c8f 100644
--- a/controller/src/main/java/org/openremote/controller/command/ExecutableCommand.java
+++ b/controller/src/main/java/org/openremote/controller/command/ExecutableCommand.java
@@ -5,5 +5,5 @@ public interface ExecutableCommand extends Command {
/**
* Send some executable command to device.
*/
- void send();
+ void send(String value);
}
diff --git a/controller/src/main/java/org/openremote/controller/command/CommandFactory.java b/controller/src/main/java/org/openremote/controller/command/ExecutableCommandFactory.java
similarity index 70%
rename from controller/src/main/java/org/openremote/controller/command/CommandFactory.java
rename to controller/src/main/java/org/openremote/controller/command/ExecutableCommandFactory.java
index 40062ca20..ecf906da9 100644
--- a/controller/src/main/java/org/openremote/controller/command/CommandFactory.java
+++ b/controller/src/main/java/org/openremote/controller/command/ExecutableCommandFactory.java
@@ -2,9 +2,9 @@ package org.openremote.controller.command;
import org.openremote.controller.model.CommandDefinition;
-public abstract class CommandFactory {
+public abstract class ExecutableCommandFactory {
- public Command getCommand(CommandDefinition commandDefinition) throws Exception {
+ public ExecutableCommand getCommand(CommandDefinition commandDefinition) throws Exception {
if (commandDefinition == null) {
throw new Exception("Null reference trying to create a protocol command");
}
@@ -20,5 +20,5 @@ public abstract class CommandFactory {
return buildCommand(commandDefinition);
}
- protected abstract Command buildCommand(CommandDefinition commandDefinition);
+ protected abstract ExecutableCommand buildCommand(CommandDefinition commandDefinition);
}
diff --git a/controller/src/main/java/org/openremote/controller/event/CommandFacade.java b/controller/src/main/java/org/openremote/controller/event/CommandFacade.java
index dfaf9a9c4..f0c93a911 100644
--- a/controller/src/main/java/org/openremote/controller/event/CommandFacade.java
+++ b/controller/src/main/java/org/openremote/controller/event/CommandFacade.java
@@ -5,16 +5,21 @@ import org.openremote.controller.model.CommandDefinition;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
+import java.util.logging.Logger;
public class CommandFacade {
+ private static final Logger LOG = Logger.getLogger(CommandFacade.class.getName());
+
final protected Map<String, CommandDefinition> namedCommands = new HashMap<>();
public CommandFacade(Collection<CommandDefinition> commandDefinitions) {
for (CommandDefinition cmd : commandDefinitions) {
- String cmdName = cmd.getProperty(CommandDefinition.COMMAND_NAME_PROPERTY);
+ String cmdName = cmd.getProperty(CommandDefinition.NAME_PROPERTY);
if (cmdName != null && !cmdName.equals("")) {
namedCommands.put(cmdName, cmd);
+ } else {
+ LOG.warning("Ignoring command definition without command name: " + cmd);
}
}
}
@@ -25,17 +30,18 @@ public class CommandFacade {
public void command(String name, String param) {
if (name == null || name.equals("")) {
- // TODO log
+ LOG.info("Empty command name, ignoring execution (are all your rules executing commands with proper names?)");
return;
}
CommandDefinition cmd = namedCommands.get(name);
if (cmd == null) {
- // TODO log
+ LOG.warning("Command definition not found, ignoring execution: " + name);
return;
}
+ LOG.fine("Preparing and executing: " + cmd);
if (param == null) {
cmd.execute();
} else {
diff --git a/controller/src/main/java/org/openremote/controller/event/CustomStateEvent.java b/controller/src/main/java/org/openremote/controller/event/CustomStateEvent.java
index 0d0725e56..7347e90a8 100644
--- a/controller/src/main/java/org/openremote/controller/event/CustomStateEvent.java
+++ b/controller/src/main/java/org/openremote/controller/event/CustomStateEvent.java
@@ -3,7 +3,7 @@ package org.openremote.controller.event;
/**
* Custom state event is a very basic event type that simply holds any arbitrary string
* as its value. No semantics or rules are applied to the value string.
- *
+ * <p>
* Custom state events are associated with 'custom' sensors in controller definition.
*/
public class CustomStateEvent extends Event<String> {
@@ -75,5 +75,15 @@ public class CustomStateEvent extends Event<String> {
&& cs.getSource().equals(this.getSource())
&& cs.getValue().equals(this.getValue());
}
+
+ @Override
+ public String toString() {
+ return "CustomStateEvent{" +
+ "sourceId=" + getSourceID() +
+ ", source='" + getSource() + "'" +
+ ", eventValue='" + eventValue + '\'' +
+ ", originalState='" + originalState + '\'' +
+ '}';
+ }
}
diff --git a/controller/src/main/java/org/openremote/controller/event/LevelEvent.java b/controller/src/main/java/org/openremote/controller/event/LevelEvent.java
index 66f9aebef..6b5befeda 100644
--- a/controller/src/main/java/org/openremote/controller/event/LevelEvent.java
+++ b/controller/src/main/java/org/openremote/controller/event/LevelEvent.java
@@ -5,7 +5,7 @@ import java.util.logging.Logger;
/**
* Level events are integer based events where values have been limited to a range of
* [0..100]
- *
+ * <p>
* Level events are associated with sensors of 'level' type in controller.xml model.
*/
public class LevelEvent extends RangeEvent {
@@ -26,7 +26,7 @@ public class LevelEvent extends RangeEvent {
value = 100;
LOG.log(java.util.logging.Level.WARNING,
"A LEVEL event was created with an invalid value : {0} (Source Sensor = {1} - {2}). " +
- "The event value has been limited to maximum value of 100.", new Object[] {value, sensorID, sensorName}
+ "The event value has been limited to maximum value of 100.", new Object[]{value, sensorID, sensorName}
);
}
@@ -34,7 +34,7 @@ public class LevelEvent extends RangeEvent {
value = 0;
LOG.log(java.util.logging.Level.WARNING,
"A LEVEL event was create with an invalid value : {0} (Source Sensor = {1} - {2}). " +
- "The event value has been limited to minimum value of 0.", new Object[] {value, sensorID, sensorName}
+ "The event value has been limited to minimum value of 0.", new Object[]{value, sensorID, sensorName}
);
}
return value;
@@ -43,9 +43,9 @@ public class LevelEvent extends RangeEvent {
/**
* Constructs a new LEVEL event with a given originating sensor ID, originating sensor name
* and event value.
- *
+ * <p>
* Level events are associated with sensors of 'level' type in controller.xml model.
- *
+ * <p>
* Level event values must be restricted to a range of [0..100].
*
* @param sourceSensorID originating sensor's ID
@@ -81,5 +81,12 @@ public class LevelEvent extends RangeEvent {
&& l.getValue().equals(this.getValue());
}
+ @Override
+ public String toString() {
+ return "LevelEvent{" +
+ "sourceId=" + getSourceID() +
+ ", source='" + getSource() + "'" +
+ "}";
+ }
}
diff --git a/controller/src/main/java/org/openremote/controller/event/RangeEvent.java b/controller/src/main/java/org/openremote/controller/event/RangeEvent.java
index ef2ca7497..8224d50e5 100644
--- a/controller/src/main/java/org/openremote/controller/event/RangeEvent.java
+++ b/controller/src/main/java/org/openremote/controller/event/RangeEvent.java
@@ -75,12 +75,15 @@ public class RangeEvent extends Event<Integer> {
&& r.rangeValue.equals(this.rangeValue);
}
-
@Override
public String toString() {
- return
- "Range Event (ID = " + getSourceID() + ", Source = '" + getSource() + "', Value = '" +
- getValue() + "', Boundaries = [" + getMinValue() + "..." + getMaxValue() + "])";
+ return "RangeEvent{" +
+ "sourceId=" + getSourceID() +
+ ", source='" + getSource() + "'" +
+ ", rangeValue=" + rangeValue +
+ ", min=" + min +
+ ", max=" + max +
+ '}';
}
}
diff --git a/controller/src/main/java/org/openremote/controller/event/SwitchEvent.java b/controller/src/main/java/org/openremote/controller/event/SwitchEvent.java
index 4213e0122..499d2ecf1 100644
--- a/controller/src/main/java/org/openremote/controller/event/SwitchEvent.java
+++ b/controller/src/main/java/org/openremote/controller/event/SwitchEvent.java
@@ -108,13 +108,14 @@ public class SwitchEvent extends Event<String> {
&& s.getValue().equals(this.getValue());
}
-
@Override
public String toString() {
- return
- "Switch Event (ID = " + getSourceID() + ", Source = '" + getSource() +
- "', Switch Value = '" + getValue() + "', Switch State = " + getState() + ")";
+ return "SwitchEvent{" +
+ "sourceId=" + getSourceID() +
+ ", source='" + getSource() + "'" +
+ ", switchValue='" + switchValue + '\'' +
+ ", switchState=" + switchState +
+ '}';
}
-
}
diff --git a/controller/src/main/java/org/openremote/controller/model/CommandDefinition.java b/controller/src/main/java/org/openremote/controller/model/CommandDefinition.java
index 7579418d0..e1fbac581 100644
--- a/controller/src/main/java/org/openremote/controller/model/CommandDefinition.java
+++ b/controller/src/main/java/org/openremote/controller/model/CommandDefinition.java
@@ -1,11 +1,8 @@
package org.openremote.controller.model;
-import org.openremote.controller.command.Command;
-import org.openremote.controller.command.CommandFactory;
import org.openremote.controller.command.ExecutableCommand;
-import org.openremote.controller.command.PullCommand;
+import org.openremote.controller.command.ExecutableCommandFactory;
-import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
@@ -21,31 +18,21 @@ public class CommandDefinition {
private static final Logger LOG = Logger.getLogger(CommandDefinition.class.getName());
/**
- * Command property name of dynamic command value for slider, colorpicker.
- * This property is temporary for holding dynamic control command value from REST API.
- * Take slider for example:
- * REST API: http://localhost:8080/controller/rest/control/{slider_id}/10
- * <b>10</b> means control command value of slider
- *
+ * Command property name that contains a logical command name that can be used by scripts,
+ * rules, REST API calls, etc.
*/
- public static final String DYNAMIC_VALUE_PROPERTY = "dynamicValue";
+ public final static String NAME_PROPERTY = "name";
/**
* Default value returned by {@link #getName()} if no name has been set in command's properties.
*/
- public final static String DEFAULT_NAME_PROPERTY_VALUE = "<no name>";
-
- /**
- * Command property name that contains a logical command name that can be used by scripts,
- * rules, REST API calls, etc.
- */
- public final static String COMMAND_NAME_PROPERTY = "name";
+ public final static String NAME_PROPERTY_DEFAULT_VALUE = "<no name>";
/**
* Command factory delegates creation of command execution model to specific protocol specific
* builders (Such as X10, KNX, one-wire, etc.)
*/
- final private CommandFactory commandFactory;
+ final private ExecutableCommandFactory executableCommandFactory;
/**
* Command's protocol identifier, such as 'knx', 'x10', 'onewire', etc. This identifier is
@@ -61,11 +48,11 @@ public class CommandDefinition {
/**
* List of generic command properties. The correspond to {@code <property>} elements nested
- * within {@code <command>} element in controller's XML definition.
- *
+ * within {@code <command>} element in controller's XML definition.
+ * <p>
* An arbitrary list of properties is allowed. Specific property names (such as
- * {@link #COMMAND_NAME_PROPERTY}) may have a special meaning.
- *
+ * {@link #NAME_PROPERTY}) may have a special meaning.
+ * <p>
* NOTE: property *names* are *not* case sensitive. All property names are converted to lower
* case.
*/
@@ -74,35 +61,24 @@ public class CommandDefinition {
/**
* Constructs a command data model.
*
- * @param commandFactory Command factory is used to construct a protocol specific command execution model
- * (for example, KNX specific commands or X10 specific commands).
- * @param id This represents the unique identifier of the command element in controller's
- * XML definition (corresponding to 'id' attribute of {@code <command>} element)
- * @param protocolType Protocol type identifier for this command. The protocol type identifier is used
- * with the command factory to identify which plugin (Java bean implementation) is
- * used to construct command's protocol specific execution model.
- * @param properties Command's properties. Arbitrary list of properties that can be used to configure
- * command instances. Certain property values such as {@link #COMMAND_NAME_PROPERTY}
- * may have special meaning. The property name,value pairs match the
- * {@code <property>} elements nested within {@code <command>} elements within
- * controller's XML document model.
+ * @param executableCommandFactory Command factory is used to construct a protocol specific command execution model
+ * (for example, KNX specific commands or X10 specific commands).
+ * @param id This represents the unique identifier of the command element in controller's
+ * XML definition (corresponding to 'id' attribute of {@code <command>} element)
+ * @param protocolType Protocol type identifier for this command. The protocol type identifier is used
+ * with the command factory to identify which plugin (Java bean implementation) is
+ * used to construct command's protocol specific execution model.
+ * @param properties Command's properties. Arbitrary list of properties that can be used to configure
+ * command instances. Certain property values such as {@link #NAME_PROPERTY}
+ * may have special meaning.
*/
- public CommandDefinition(CommandFactory commandFactory, int id, String protocolType, Map<String, String> properties) {
- this.commandFactory = commandFactory;
+ public CommandDefinition(ExecutableCommandFactory executableCommandFactory, int id, String protocolType, Map<String, String> properties) {
+ this.executableCommandFactory = executableCommandFactory;
this.id = id;
this.protocolType = protocolType;
this.properties = properties;
}
- public CommandDefinition(CommandDefinition original) {
- this(
- original.commandFactory,
- original.id,
- original.protocolType,
- new HashMap<>(original.properties)
- );
- }
-
/**
* Returns the unique identifier of the command that corresponds to 'id' attribute of
* {@code <command>} element in controller's XML definition.
@@ -116,13 +92,13 @@ public class CommandDefinition {
/**
* Returns a command's name property if present.
*
- * @return commands name, or a default {@link #DEFAULT_NAME_PROPERTY_VALUE} string if
+ * @return commands name, or a default {@link #NAME_PROPERTY_DEFAULT_VALUE} string if
* name property is not present
*/
public String getName() {
- String name = getProperty(COMMAND_NAME_PROPERTY);
+ String name = getProperty(NAME_PROPERTY);
if (name == null || name.equals("")) {
- return DEFAULT_NAME_PROPERTY_VALUE;
+ return NAME_PROPERTY_DEFAULT_VALUE;
}
return name;
}
@@ -158,30 +134,21 @@ public class CommandDefinition {
}
/**
- * Executes a parameterized command. This normally means a device protocol is used to
- * communicate with some physical device. Command parameterization is typically used
- * with commands that allow setting distinct values, such as setting a volume to a specific
- * distinct level, setting blinds to a specific distinct location, etc.
+ * Build an {@link ExecutableCommand} from this definition and execute it with the given argument.
*
- * @param param command parameter value
+ * @param arg command parameter value
*/
- public void execute(String param) {
+ public void execute(String arg) {
try {
- // Work on a copy of this, so we can modify it for this execution (bad design)
- CommandDefinition commandDefinition = new CommandDefinition(this);
- if (param != null) {
- commandDefinition.properties.put(CommandDefinition.DYNAMIC_VALUE_PROPERTY, param);
- }
- Command command = commandFactory.getCommand(commandDefinition);
-
- if (command instanceof ExecutableCommand) {
- ExecutableCommand writeCommand = (ExecutableCommand) command;
- writeCommand.send();
- } else if (command instanceof PullCommand) {
- LOG.severe("Execution of read commands not implemented yet.");
- } else {
- LOG.log(Level.SEVERE, "Cannot execute: " + this);
+ ExecutableCommand command = executableCommandFactory.getCommand(this);
+ if (command == null) {
+ LOG.log(Level.WARNING,
+ "No command was produced (can the protocol build an ExecutableCommand?): " + this
+ );
+ return;
}
+ LOG.fine("Executing command '" + command + "' with: " + arg);
+ command.send(arg);
} catch (Throwable t) {
LOG.log(Level.SEVERE, "Unable to execute command: " + this, t);
}
diff --git a/controller/src/main/java/org/openremote/controller/model/Sensor.java b/controller/src/main/java/org/openremote/controller/model/Sensor.java
index 28fb0cc1d..75123f9b7 100644
--- a/controller/src/main/java/org/openremote/controller/model/Sensor.java
+++ b/controller/src/main/java/org/openremote/controller/model/Sensor.java
@@ -18,23 +18,23 @@ import java.util.logging.Logger;
* Sensors abstract incoming events from devices, either through pulling/polling or
* listening to devices that actively push their state changes. Sensors operate on
* commands to execute pull or push operations with devices.
- *
+ * <p>
* Each pulling sensor (for passive devices) has a thread associated with it. Sensors
* bound to push commands do not create threads of their own but the command
* implementations themselves are usually multi-threaded.
- *
+ * <p>
* Each sensor can have list of properties which it makes available to implementations of
* push or pull commands. These properties may be used by protocol implementers to
* direct their event producer output values to suit the sensor's configuration.
- *
+ * <p>
* Sensors are registered with
* {@link org.openremote.controller.statuscache.StatusCache device state cache}. Sensors create
* {@link org.openremote.controller.event.Event} which represent the data from event
* producers and are passed by cache to
* {@link org.openremote.controller.event.EventProcessor}s.
- *
+ * <p>
* Therefore the object hierarchy for sensors is as follows:
- *
+ * <p>
* <pre>{@code Cache (one) <--> (many) Sensor (one) <--> (one) Event Producer}</pre>
*
* Event producers are created by third party integrators where as cache and sensors are part of
@@ -82,7 +82,7 @@ public abstract class Sensor {
* An event producer is a protocol handler that can be customized to return values to a sensor.
* Therefore the sensor implementation remains type (as in Java class type) and protocol
* independent and delegates these protocol specific tasks to event producer implementations.
- *
+ * <p>
* Two sub-categories of event producers exist today: pull and push commands. These are dealt
* differently in that pull commands are actively polled by
* the sensor while push commands produce events to the controller at their own schedule.
@@ -168,7 +168,7 @@ public abstract class Sensor {
/**
* Returns sensor's properties. Properties are simply string based name-value mappings.
* Concrete sensor implementations may specify which particular properties they expose.
- *
+ * <p>
* The returned map does not reference this sensor instance and can be modified freely.
*
* @return sensor properties or an empty collection
@@ -183,7 +183,7 @@ public abstract class Sensor {
/**
* Call path for push commands. Allow direct update of the sensor's value in the controller's
* global state cache.
- *
+ * <p>
* Before updating the state cache, the value is first validated by concrete sensor
* implementation's {@link Sensor#processEvent(String)} method.
*
@@ -373,18 +373,18 @@ public abstract class Sensor {
/**
* Returns the current state of this sensor.
- *
+ * <p>
* If the sensor is bound to a pull command implementation, the command is invoked --
* this may yield an active request using the connecting transport to device unless the
* command implementation caches certain values and returns them from memory.
- *
+ * <p>
* In case of a push command, this method does not invoke anything on the command itself
* but returns the last stored state from the controller's device state cache associated with
* this sensor's ID. A push command implementation is responsible of actively updating and
* inserting the device state values into the controller's cache.
- *
+ * <p>
* In case of errors, {@link #UNKNOWN_STATUS} is returned.
- *
+ * <p>
* This default read() implementation does not validate the input from protocol pull commands
* in any way (other than handling implementation errors that yield runtime exceptions).
* concrete subclasses should override and implement {@link Sensor#processEvent(String)}
@@ -407,7 +407,7 @@ public abstract class Sensor {
// device state...
PullCommand command = (PullCommand) eventProducerCommand;
try {
- return command.read(Sensor.this);
+ return command.read(Sensor.this);
} catch (Throwable t) {
LOG.log(Level.SEVERE, "Implementation error in pull command: " + eventProducerCommand, t);
return UNKNOWN_STATUS;
@@ -425,7 +425,7 @@ public abstract class Sensor {
* A definition of an event that can be used when either an error occurs in sensor implementation
* (or in the underlying protocol implementation) or if the initial device state has not been
* fetched yet.
- *
+ * <p>
* The value returned by this event is defined in {@link #UNKNOWN_STATUS}.
*/
public static class UnknownEvent extends Event<String> {
@@ -466,11 +466,19 @@ public abstract class Sensor {
public String serialize() {
return UNKNOWN_STATUS;
}
+
+ @Override
+ public String toString() {
+ return "UnknownEvent{" +
+ "sourceId=" + getSourceID() +
+ ", source='" + getSource() + "'" +
+ "}";
+ }
}
/**
* Test sensor object equality based on unique identifier (as returned by {@link #getSensorID}.
- *
+ * <p>
* Subclasses are considered equal, despite what their data values are, as long as the sensor
* ID is equal.
*
diff --git a/controller/src/test/groovy/org/openremote/test/rules/Bak.java b/controller/src/test/groovy/org/openremote/test/rules/Bak.java
index 318c60c94..5e689d89e 100644
--- a/controller/src/test/groovy/org/openremote/test/rules/Bak.java
+++ b/controller/src/test/groovy/org/openremote/test/rules/Bak.java
@@ -2,394 +2,6 @@ package org.openremote.test.rules;
public class Bak {
-
-//
-// /**
-// * Test a mixed deployment of multiple rules, some from drools rule language,
-// * others from CSV decision table.
-// *
-// * @throws Exception if test fails
-// */
-// @Test
-// public void testMixedDRLCSVDeployment() throws Exception {
-// String newResourcePath = AllTests.getAbsoluteFixturePath()
-// .resolve("statuscache/rules/mixed/").toString();
-//
-// config.setResourcePath(newResourcePath);
-//
-// RuleEngine rules = new RuleEngine();
-// EventGrab grab = new EventGrab();
-//
-// List<EventProcessor> processors = new ArrayList<EventProcessor>();
-// processors.add(rules);
-// processors.add(grab);
-//
-// CommandCounter commandCounter = new CommandCounter();
-//
-// StatusCache cache = createCache(processors, "commandCounter", commandCounter, "count");
-//
-//
-// // should not trigger commands...
-//
-// Switch sw = new Switch(1, "test", "on", Switch.State.ON);
-//
-// cache.update(sw);
-// Event evt = grab.event;
-//
-// Assert.assertTrue(evt.getSource().equals("test"));
-// Assert.assertTrue(evt.getSourceID() == 1);
-// Assert.assertTrue(evt.getValue().equals("on"));
-// Assert.assertTrue(evt.serialize().equals("on"));
-// Assert.assertTrue(evt instanceof Switch);
-// Assert.assertTrue(evt.equals(sw));
-// Assert.assertTrue(evt == sw);
-//
-// Switch swevt = (Switch) evt;
-//
-// Assert.assertTrue(swevt.getState().equals(Switch.State.ON));
-//
-// Assert.assertTrue(grab.count == 1);
-// Assert.assertTrue(commandCounter.count == 0);
-//
-//
-// // Should get its value modified by EventMod.drl above range max...
-//
-// Level level = new Level(123, "test level mod", 30);
-//
-// cache.registerSensor(new LevelSensor("test level mod", 123, cache, new TestCommand(), 1));
-//
-// cache.update(level);
-//
-// Thread.sleep(2000);
-//
-// evt = grab.event;
-//
-// Assert.assertTrue(evt.getSource().equals("test level mod"));
-//
-// Assert.assertTrue(
-// "Was expecting 100, got " + evt.getValue(),
-// evt.getValue().equals(100)
-// );
-//
-// Assert.assertTrue(evt.serialize().equals("100"));
-// Assert.assertTrue(evt instanceof Level);
-// Assert.assertTrue(!evt.equals(level));
-// Assert.assertTrue(evt != level);
-//
-// Level l1 = (Level) evt;
-// Assert.assertTrue(l1.getValue() == 100);
-//
-// Assert.assertTrue(grab.count == 2);
-//
-//
-// // should execute command with param 55...
-//
-// level = new Level(555, "test level mod 555", 101);
-//
-// cache.update(level);
-// evt = grab.event;
-//
-// Assert.assertTrue(evt.getSource().equals("test level mod 555"));
-// Assert.assertTrue(evt.getSourceID() == 555);
-// Assert.assertTrue(evt.getValue().equals(100));
-// Assert.assertTrue(evt.serialize().equals("100"));
-// Assert.assertTrue(evt instanceof Level);
-// Assert.assertTrue(evt.equals(level));
-// Assert.assertTrue(evt == level);
-//
-//
-// Assert.assertTrue(commandCounter.count == 1);
-// Assert.assertTrue(commandCounter.lastValue.equals("55"));
-// Assert.assertTrue(grab.count == 3);
-//
-//
-// // should execute command with param 6666...
-//
-// level = new Level(666, "test level mod 666", 1);
-//
-// cache.update(level);
-// evt = grab.event;
-//
-// Assert.assertTrue(evt.getSource().equals("test level mod 666"));
-// Assert.assertTrue(evt.getSourceID() == 666);
-// Assert.assertTrue(evt.getValue().equals(1));
-// Assert.assertTrue(evt.serialize().equals("1"));
-//
-// Assert.assertTrue(commandCounter.count == 2);
-// Assert.assertTrue(commandCounter.lastValue.equals("6666"));
-// Assert.assertTrue(grab.count == 4);
-//
-//
-// // should execute command with param -77
-//
-// level = new Level(777, "test level mod 777", 10);
-//
-// cache.update(level);
-// evt = grab.event;
-//
-// Assert.assertTrue(evt.getSource().equals("test level mod 777"));
-// Assert.assertTrue(evt.getSourceID() == 777);
-// Assert.assertTrue(evt.getValue().equals(10));
-// Assert.assertTrue(evt.serialize().equals("10"));
-//
-// Assert.assertTrue(commandCounter.count == 3);
-// Assert.assertTrue(commandCounter.lastValue.equals("-77"));
-// Assert.assertTrue(grab.count == 5);
-// }
-//
-//
-// /**
-// * Test rule engine initialization in case of a broken CSV file (should not
-// * throw an exception that propagates through the event processor).
-// *
-// * @throws Exception if test fails
-// */
-// @Test
-// public void testDecisionTableNoRuleSet() throws Exception {
-// String newResourcePath = AllTests.getAbsoluteFixturePath()
-// .resolve("statuscache/rules/dtable-noruleset/").toString();
-//
-// config.setResourcePath(newResourcePath);
-//
-// RuleEngine rules = new RuleEngine();
-// rules.init();
-//
-// rules.start(new LifeCycleEvent(null));
-// }
-//
-//
-// /**
-// * Test rule engine initialization in case of a incorrectly defined decision table
-// * (should not propagate exceptions through event processor implementation).
-// *
-// * @throws Exception if test fails
-// */
-// @Test
-// public void testDecisionTableIncorrectDefinition() throws Exception {
-// String newResourcePath = AllTests.getAbsoluteFixturePath()
-// .resolve("statuscache/rules/dtable-incorrect-definition/").toString();
-//
-// config.setResourcePath(newResourcePath);
-//
-// RuleEngine rules = new RuleEngine();
-// rules.init();
-//
-// rules.start(new LifeCycleEvent(null));
-// }
-//
-//
-// /**
-// * Test basic decision table deployment and operation to modify the processed events.
-// *
-// * @throws Exception if test fails
-// */
-// @Test
-// public void testDecisionTable() throws Exception {
-// String newResourcePath = AllTests.getAbsoluteFixturePath()
-// .resolve("statuscache/rules/dtable/").toString();
-//
-// config.setResourcePath(newResourcePath);
-//
-// RuleEngine rules = new RuleEngine();
-// rules.init();
-// EventGrab grab = new EventGrab();
-//
-// List<EventProcessor> processors = new ArrayList<EventProcessor>();
-// processors.add(rules);
-// processors.add(grab);
-//
-// CommandCounter commandCounter = new CommandCounter();
-// StatusCache cache = createCache(processors, "commandCounter", commandCounter, "count");
-//
-//
-// Switch sw = new Switch(555, "test555", "on", Switch.State.ON);
-//
-// cache.update(sw);
-//
-// Assert.assertTrue(
-// "Expected 'triggered', got '" + commandCounter.lastValue + "'",
-// commandCounter.lastValue.equals("triggered")
-// );
-//
-// sw = new Switch(666, "test666", "on", Switch.State.ON);
-//
-// cache.update(sw);
-//
-// Assert.assertTrue(commandCounter.lastValue.equals("started"));
-//
-// sw = new Switch(777, "test777", "on", Switch.State.ON);
-//
-// cache.update(sw);
-//
-// Assert.assertTrue(commandCounter.lastValue.equals("good"));
-// }
-//
-//
-// /**
-// * TODO
-// *
-// * @throws Exception if test fails
-// */
-// @Test
-// public void vacationTest() throws Exception {
-// String newResourcePath = AllTests.getAbsoluteFixturePath()
-// .resolve("statuscache/rules/holiday-example/").toString();
-//
-// config.setResourcePath(newResourcePath);
-//
-// RuleEngine rules = new RuleEngine();
-// EventGrab grab = new EventGrab();
-//
-// List<EventProcessor> processors = new ArrayList<EventProcessor>();
-// processors.add(rules);
-// processors.add(grab);
-//
-// CommandCounter tempCommands = new CommandCounter();
-//
-// StatusCache cache = createCache(processors, "commandCounter", tempCommands, "temp");
-//
-//
-// Assert.assertTrue(grab.count == 0);
-//
-//
-// {
-// CustomState state = new CustomState(20, "time of day", "day");
-//
-// cache.update(state);
-//
-// Event evt = grab.event;
-//
-// Assert.assertTrue(grab.count == 1);
-//
-// Assert.assertTrue(evt.getSourceID() == 20);
-// Assert.assertTrue(evt.getSource().equals("time of day"));
-// Assert.assertTrue(evt.getValue().equals("day"));
-// Assert.assertTrue(evt instanceof CustomState);
-// Assert.assertTrue(evt.equals(state));
-// Assert.assertTrue(evt == state);
-//
-//
-// Assert.assertTrue(tempCommands.count == 1);
-//
-// Assert.assertTrue(
-// "Expected last command value '21', got '" + tempCommands.lastValue + "'",
-// tempCommands.lastValue.equals("21")
-// );
-// }
-//
-//
-// {
-// CustomState state = new CustomState(20, "time of day", "night");
-//
-// cache.update(state);
-//
-// Event evt = grab.event;
-//
-// Assert.assertTrue(grab.count == 2);
-//
-// Assert.assertTrue(evt.getSourceID() == 20);
-// Assert.assertTrue(evt.getSource().equals("time of day"));
-// Assert.assertTrue(evt.getValue().equals("night"));
-// Assert.assertTrue(evt instanceof CustomState);
-// Assert.assertTrue(evt.equals(state));
-// Assert.assertTrue(evt == state);
-//
-//
-// Assert.assertTrue(tempCommands.count == 2);
-//
-// Assert.assertTrue(
-// "Expected last command value '18', got '" + tempCommands.lastValue + "'",
-// tempCommands.lastValue.equals("18")
-// );
-// }
-//
-//
-// {
-// Switch sw = new Switch(1, "vacation start", "on", Switch.State.ON);
-//
-// cache.update(sw);
-//
-// Event evt = grab.event;
-//
-// Assert.assertTrue(grab.count == 3);
-//
-// Assert.assertTrue(evt.getSourceID() == 1);
-// Assert.assertTrue(evt.getSource().equals("vacation start"));
-// Assert.assertTrue(evt instanceof Switch);
-// Assert.assertTrue(evt.equals(sw));
-// Assert.assertTrue(evt == sw);
-//
-// Assert.assertTrue(
-// "Expected command count 3, got " + tempCommands.count,
-// tempCommands.count == 3
-// );
-//
-// Assert.assertTrue(
-// "Expected last command value '15', got '" + tempCommands.lastValue + "'",
-// tempCommands.lastValue.equals("15")
-// );
-//
-// }
-//
-//
-// {
-// CustomState state = new CustomState(20, "time of day", "day");
-//
-// cache.update(state);
-//
-// Event evt = grab.event;
-//
-// Assert.assertTrue(grab.count == 4);
-//
-// Assert.assertTrue(evt.getSourceID() == 20);
-// Assert.assertTrue(evt.getSource().equals("time of day"));
-// Assert.assertTrue(evt.getValue().equals("day"));
-// Assert.assertTrue(evt instanceof CustomState);
-// Assert.assertTrue(evt.equals(state));
-// Assert.assertTrue(evt == state);
-//
-//
-// Assert.assertTrue(
-// "Expected command count 4, got " + tempCommands.count,
-// tempCommands.count == 4
-// );
-//
-// Assert.assertTrue(
-// "Expected last command value '15', got '" + tempCommands.lastValue + "'",
-// tempCommands.lastValue.equals("15")
-// );
-// }
-//
-//
-// {
-// Switch sw = new Switch(1, "vacation end", Switch.State.OFF.serialize(), Switch.State.ON);
-//
-// cache.update(sw);
-//
-// Event evt = grab.event;
-//
-// Assert.assertTrue(grab.count == 5);
-//
-// Assert.assertTrue(evt.getSourceID() == 1);
-// Assert.assertTrue(evt.getSource().equals("vacation end"));
-// Assert.assertTrue(evt instanceof Switch);
-// Assert.assertTrue(evt.equals(sw));
-// Assert.assertTrue(evt == sw);
-//
-// Assert.assertTrue(
-// "Expected command count 5, got " + tempCommands.count,
-// tempCommands.count == 5
-// );
-//
-// Assert.assertTrue(
-// "Expected last command value '21', got '" + tempCommands.lastValue + "'",
-// tempCommands.lastValue.equals("21")
-// );
-//
-// }
-//
-// }
-//
//
// /**
// * TODO
@@ -1495,83 +1107,6 @@ public class Bak {
// }
//
// }
-//
-//
-// // Helpers --------------------------------------------------------------------------------------
-//
-//
-// private StatusCache createCache(List<EventProcessor> processors,
-// String protocolType, CommandBuilder commandBuilder,
-// String commandName) throws Exception {
-// ChangedStatusTable cst = new ChangedStatusTable();
-// EventProcessorChain epc = new EventProcessorChain();
-//
-// epc.setEventProcessors(processors);
-// epc.init();
-//
-// StatusCache cache = new StatusCache(cst, epc);
-//
-// Map<String, CommandBuilder> builders = new HashMap<String, CommandBuilder>();
-// builders.put(protocolType, commandBuilder);
-//
-// CommandFactory cf = new CommandFactory(builders);
-//
-// Element cmdElement = new Element("command", ModelBuilder.SchemaVersion.OPENREMOTE_NAMESPACE);
-// cmdElement.setAttribute("id", "10");
-// cmdElement.setAttribute("protocol", protocolType);
-//
-// Element nameProp = new Element("property", ModelBuilder.SchemaVersion.OPENREMOTE_NAMESPACE);
-// nameProp.setAttribute("name", "name");
-// nameProp.setAttribute("value", commandName);
-//
-// Set<Element> content = new HashSet<Element>();
-// content.add(nameProp);
-//
-// cmdElement.addContent(content);
-//
-// Version20CommandBuilder cmdBuilder = new Version20CommandBuilder(cf);
-// Command cmd = cmdBuilder.build(cmdElement);
-//
-// Set<Command> commands = new HashSet<Command>();
-// commands.add(cmd);
-//
-// cache.initializeEventContext(commands);
-//
-// cache.start();
-//
-// return cache;
-// }
-//
-//
-// // Nested Classes -------------------------------------------------------------------------------
-//
-
-// private static class CommandCounter implements CommandBuilder {
-// private int count = 0;
-// private String lastValue = "<nothing>";
-//
-//
-// @Override
-// public org.openremote.controller.command.Command build(Element el) {
-// count++;
-//
-// Attribute attribute = el.getAttribute(
-// org.openremote.controller.command.Command.DYNAMIC_VALUE_ATTR_NAME
-// );
-//
-// if (attribute != null) {
-// lastValue = attribute.getValue();
-// }
-//
-// return new ExecutableCommand() {
-// @Override
-// public void send() {
-//
-// }
-// };
-// }
-// }
-//
}
diff --git a/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy
index d16afd52e..91a990f5c 100644
--- a/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy
+++ b/controller/src/test/groovy/org/openremote/test/rules/MixedWithErrorsTest.groovy
@@ -23,7 +23,7 @@ import java.util.stream.Stream
*/
class MixedWithErrorsTest extends Specification implements ContainerTrait {
- def "Sensor event replaced by rule-triggered event"() {
+ def "Execute good rules - ignore broken rules"() {
given: "some sensor event processors and rules"
def ruleEngineProcessor = new RuleEngine() {
diff --git a/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy
index 6ad2379da..fdaa3bfad 100644
--- a/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy
+++ b/controller/src/test/groovy/org/openremote/test/rules/RuleExecutionLoggerTest.groovy
@@ -36,7 +36,7 @@ class RuleExecutionLoggerTest extends Specification implements ContainerTrait {
KieFileSystem kfs = kieServices.newKieFileSystem()
kfs.writeKModuleXML(kieModuleModel.toXML())
- kfs.write(ResourceFactory.newClassPathResource("org/openremote/test/rules/TestRuleFiring.drl")
+ kfs.write(ResourceFactory.newClassPathResource("org/openremote/test/rules/simple/TestRuleFiring.drl")
);
def kieBuilder = kieServices.newKieBuilder(kfs).buildAll();
diff --git a/controller/src/test/groovy/org/openremote/test/rules/EventModTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovy
similarity index 95%
rename from controller/src/test/groovy/org/openremote/test/rules/EventModTest.groovy
rename to controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovy
index 1416c8f18..56052805d 100644
--- a/controller/src/test/groovy/org/openremote/test/rules/EventModTest.groovy
+++ b/controller/src/test/groovy/org/openremote/test/rules/SimpleRuleTest.groovy
@@ -21,7 +21,7 @@ import static org.kie.api.io.ResourceType.DRL
* Basic rule engine test, trigger a rule through an event.
* The rule dispatches a new event, replacing the original event.
*/
-class EventModTest extends Specification implements ContainerTrait {
+class SimpleRuleTest extends Specification implements ContainerTrait {
def "Sensor event replaced by rule-triggered event"() {
@@ -31,7 +31,7 @@ class EventModTest extends Specification implements ContainerTrait {
protected Stream<Resource> getResources(KieServices kieServices) {
Stream.of(
kieServices.getResources().newClassPathResource(
- "org/openremote/test/rules/EventMod.drl"
+ "org/openremote/test/rules/simple/EventMod.drl"
).setResourceType(DRL)
)
}
diff --git a/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovy b/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovy
new file mode 100644
index 000000000..768259cfc
--- /dev/null
+++ b/controller/src/test/groovy/org/openremote/test/rules/VacationTest.groovy
@@ -0,0 +1,116 @@
+package org.openremote.test.rules
+
+import org.kie.api.KieServices
+import org.kie.api.io.Resource
+import org.openremote.controller.ControllerService
+import org.openremote.controller.command.ExecutableCommand
+import org.openremote.controller.command.ExecutableCommandFactory
+import org.openremote.controller.event.CommandFacade
+import org.openremote.controller.event.CustomStateEvent
+import org.openremote.controller.event.EventProcessorChain
+import org.openremote.controller.event.SwitchEvent
+import org.openremote.controller.model.CommandDefinition
+import org.openremote.controller.rules.RuleEngine
+import org.openremote.test.ContainerTrait
+import org.openremote.test.util.EventGrabProcessor
+import spock.lang.Specification
+
+import java.util.stream.Stream
+
+import static org.kie.api.io.ResourceType.DRL
+
+class VacationTest extends Specification implements ContainerTrait {
+
+ def "Vacation example"() {
+
+ given: "event processors and rules"
+ def ruleEngineProcessor = new RuleEngine() {
+ @Override
+ protected Stream<Resource> getResources(KieServices kieServices) {
+ Stream.of(
+ kieServices.getResources().newClassPathResource(
+ "org/openremote/test/rules/vacation/Vacation.drl"
+ ).setResourceType(DRL)
+ )
+ }
+ }
+ def grabProcessor = new EventGrabProcessor();
+
+ String lastCommandValue = null
+ int totalCommandCount = 0
+ def commandFactory = new ExecutableCommandFactory() {
+ @Override
+ protected ExecutableCommand buildCommand(CommandDefinition commandDefinition) {
+ return new ExecutableCommand() {
+ @Override
+ void send(String value) {
+ lastCommandValue = value
+ totalCommandCount++
+ }
+ }
+ }
+ }
+ def commandDefinitions = [
+ new CommandDefinition(commandFactory, 11, "test", [(CommandDefinition.NAME_PROPERTY): "temp"])
+ ]
+ def commandFacade = new CommandFacade(commandDefinitions)
+ def eventProcessorChain = new EventProcessorChain(
+ commandFacade,
+ ruleEngineProcessor,
+ grabProcessor
+ )
+
+ and: "the started controller server"
+ def controllerService = new ControllerService(eventProcessorChain)
+ def services = Stream.of(controllerService)
+ def serverPort = findEphemeralPort()
+ def container = startContainer(defaultConfig(serverPort), services)
+
+ when: "the time of day is day"
+ def customStateEvent = new CustomStateEvent(222, "time of day", "day");
+ controllerService.getCache().update(customStateEvent);
+
+ and: "we wait a bit for the rules to fire"
+ Thread.sleep(100);
+
+ then: "the temperature should be set"
+ lastCommandValue == "21"
+ totalCommandCount == 1
+
+ when: "the time of day is night"
+ customStateEvent = new CustomStateEvent(222, "time of day", "night");
+ controllerService.getCache().update(customStateEvent);
+
+ and: "we wait a bit for the rules to fire"
+ Thread.sleep(100);
+
+ then: "the temperature should be set"
+ lastCommandValue == "18"
+ totalCommandCount == 2
+
+ when: "we go on vacation"
+ def switchEvent = new SwitchEvent(333, "vacation start", "on", SwitchEvent.State.ON);
+ controllerService.getCache().update(switchEvent);
+
+ and: "we wait a bit for the rules to fire"
+ Thread.sleep(100);
+
+ then: "the temperature should be set"
+ lastCommandValue == "15"
+ totalCommandCount == 3
+
+ when: "the time of day is day"
+ customStateEvent = new CustomStateEvent(222, "time of day", "day");
+ controllerService.getCache().update(customStateEvent);
+
+ and: "we wait a bit for the rules to fire"
+ Thread.sleep(100);
+
+ then: "the temperature should be set"
+ lastCommandValue == "15"
+ totalCommandCount == 1
+
+ cleanup: "the server should be stopped"
+ stopContainer(container)
+ }
+}
diff --git a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drl b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drl
index aca68724a..1fe50ae29 100644
--- a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drl
+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/EventMod.drl
@@ -1,4 +1,4 @@
-package org.openremote.test.rules
+package org.openremote.test.rules;
import org.openremote.controller.event.*;
diff --git a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/IncorrectRule.drl b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/IncorrectRule.drl
index f1933cbb0..be2aaa740 100644
--- a/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/IncorrectRule.drl
+++ b/controller/src/test/resources/org/openremote/test/rules/mixed-with-errors/IncorrectRule.drl
@@ -1,4 +1,4 @@
-package org.openremote.test.rules
+package org.openremote.test.rules;
import org.openremote.controller.event.*;
diff --git a/controller/src/test/resources/org/openremote/test/rules/EventMod.drl b/controller/src/test/resources/org/openremote/test/rules/simple/EventMod.drl
similarity index 100%
rename from controller/src/test/resources/org/openremote/test/rules/EventMod.drl
rename to controller/src/test/resources/org/openremote/test/rules/simple/EventMod.drl
diff --git a/controller/src/test/resources/org/openremote/test/rules/TestRuleFiring.drl b/controller/src/test/resources/org/openremote/test/rules/simple/TestRuleFiring.drl
similarity index 100%
rename from controller/src/test/resources/org/openremote/test/rules/TestRuleFiring.drl
rename to controller/src/test/resources/org/openremote/test/rules/simple/TestRuleFiring.drl
diff --git a/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drl b/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drl
new file mode 100644
index 000000000..023997334
--- /dev/null
+++ b/controller/src/test/resources/org/openremote/test/rules/vacation/Vacation.drl
@@ -0,0 +1,70 @@
+package org.openremote.test.rules;
+
+global org.openremote.controller.event.CommandFacade execute;
+
+import org.openremote.controller.command.*;
+import org.openremote.controller.event.*;
+import org.openremote.controller.model.*;
+
+/*
+ * This example demonstrates creation of new facts from within the rules, in this
+ * case a vacation object that can be used to determine differing behavior on event
+ * actions.
+ */
+
+declare Vacation
+ onVacation : boolean
+end
+
+/* Insert a new vacation fact */
+
+rule "I'm going on vacation"
+when
+ Event ( source == "vacation start" )
+then
+ Vacation vacation = new Vacation();
+ insert ( vacation );
+end
+
+/* Retract the vacation fact */
+
+rule "I'm back from vacation"
+when
+ Event ( source == "vacation end" )
+ $vacation : Vacation()
+then
+ retract ( $vacation );
+end
+
+/* Set night temperatures differently depending on presence of vacation fact */
+
+rule "Set Night Temperature"
+when
+ CustomStateEvent( source == "time of day", value == "night" ) and not Vacation()
+then
+ execute.command("temp", 18);
+end
+
+rule "Set Night Temperature when on Vacation"
+when
+ CustomStateEvent ( source == "time of day", value == "night" ) and exists Vacation()
+then
+ execute.command("temp", 15);
+end
+
+/* Set day temperatures differently depending on the presence of vacation fact */
+
+rule "Set Day Temperature"
+when
+ CustomStateEvent ( source == "time of day", value == "day" ) and not Vacation()
+then
+ execute.command("temp", 21);
+end
+
+rule "Set Day Temperature when on Vacation"
+when
+ Event ( source == "time of day", value == "day" ) and exists Vacation()
+then
+ execute.command("temp", 15);
+end
+
diff --git a/manager/test/build.gradle b/manager/test/build.gradle
index cf2ef0d0f..3b0a3e1a6 100644
--- a/manager/test/build.gradle
+++ b/manager/test/build.gradle
@@ -10,6 +10,7 @@ dependencies {
compile project(":manager:connector:controller2")
compile "junit:junit:$junitVersion"
+ compile "org.spockframework:spock-core:$spockVersion"
}
test {