This repository has been archived by the owner on May 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 789
/
RuleEngine.java
1513 lines (1391 loc) · 60.3 KB
/
RuleEngine.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) 1997, 2015 by ProSyst Software GmbH and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.automation.core.internal;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.smarthome.automation.Action;
import org.eclipse.smarthome.automation.Condition;
import org.eclipse.smarthome.automation.Module;
import org.eclipse.smarthome.automation.Rule;
import org.eclipse.smarthome.automation.RuleRegistry;
import org.eclipse.smarthome.automation.RuleStatus;
import org.eclipse.smarthome.automation.RuleStatusDetail;
import org.eclipse.smarthome.automation.RuleStatusInfo;
import org.eclipse.smarthome.automation.StatusInfoCallback;
import org.eclipse.smarthome.automation.Trigger;
import org.eclipse.smarthome.automation.core.internal.RuleEngineCallbackImpl.TriggerData;
import org.eclipse.smarthome.automation.core.internal.composite.CompositeModuleHandlerFactory;
import org.eclipse.smarthome.automation.core.util.ConnectionValidator;
import org.eclipse.smarthome.automation.handler.ActionHandler;
import org.eclipse.smarthome.automation.handler.ConditionHandler;
import org.eclipse.smarthome.automation.handler.ModuleHandler;
import org.eclipse.smarthome.automation.handler.ModuleHandlerFactory;
import org.eclipse.smarthome.automation.handler.RuleEngineCallback;
import org.eclipse.smarthome.automation.handler.TriggerHandler;
import org.eclipse.smarthome.automation.type.ActionType;
import org.eclipse.smarthome.automation.type.CompositeActionType;
import org.eclipse.smarthome.automation.type.CompositeConditionType;
import org.eclipse.smarthome.automation.type.CompositeTriggerType;
import org.eclipse.smarthome.automation.type.ConditionType;
import org.eclipse.smarthome.automation.type.Input;
import org.eclipse.smarthome.automation.type.ModuleType;
import org.eclipse.smarthome.automation.type.ModuleTypeRegistry;
import org.eclipse.smarthome.automation.type.Output;
import org.eclipse.smarthome.automation.type.TriggerType;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameter;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameter.Type;
import org.eclipse.smarthome.config.core.ConfigUtil;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.core.common.registry.RegistryChangeListener;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
/**
* This class is used to initialized and execute {@link Rule}s added in rule engine. Each Rule has associated
* {@link RuleStatusInfo} object which shows status and status details of of the Rule. The states are self excluded and
* they are:
* <LI>disabled - the rule is temporary not available. This status is set by the user.
* <LI>not initialized -
* the rule is enabled, but it still is not working because some of the module handlers are not available or its module
* types or template is not resolved. The initialization problem is described by the status details
* <LI>idle - the rule
* is enabled and initialized and it is waiting for triggering events.
* <LI>running - the rule is enabled and initialized
* and it is executing at the moment. When the execution is finished, it goes to the idle state.
*
* @author Yordan Mihaylov - Initial Contribution
* @author Kai Kreuzer - refactored (managed) provider, registry implementation and customized modules
* @author Benedikt Niehues - change behavior for unregistering ModuleHandler
*
*/
@SuppressWarnings("rawtypes")
public class RuleEngine implements RegistryChangeListener<ModuleType> {
/**
* Constant defining separator between module uid and output name.
*/
public static final char OUTPUT_SEPARATOR = '.';
/**
* Prefix of {@link Rule}'s UID created by the rule engine.
*/
public static final String ID_PREFIX = "rule_"; //$NON-NLS-1$
/**
* Default value of delay between rule's re-initialization tries.
*/
public static final long DEFAULT_REINITIALIZATION_DELAY = 500;
/**
* Delay between rule's re-initialization tries.
*/
public static final String CONFIG_PROPERTY_REINITIALIZATION_DELAY = "rule.reinitialization.delay";
/**
* Delay between rule's re-initialization tries.
*/
private long scheduleReinitializationDelay;
/**
* {@link Map} of rule's id to corresponding {@link RuleEngineCallback}s. For each {@link Rule} there is one and
* only one rule callback.
*/
private Map<String, RuleEngineCallbackImpl> reCallbacks = new HashMap<String, RuleEngineCallbackImpl>();
/**
* {@link Map} of module type UIDs to rules where these module types participated.
*/
private Map<String, Set<String>> mapModuleTypeToRules = new HashMap<String, Set<String>>();
/**
* {@link Map} of created rules. It contains all rules added to rule engine independent if they are initialized or
* not. The relation is rule's id to {@link Rule} object.
*/
private Map<String, RuntimeRule> rules;
/**
* {@link Map} system module type to corresponding module handler factories.
*/
private Map<String, ModuleHandlerFactory> moduleHandlerFactories;
private Set<ModuleHandlerFactory> allModuleHandlerFactories = new CopyOnWriteArraySet<>();
/**
* Locker which does not permit rule initialization when the rule engine is stopping.
*/
private boolean isDisposed = false;
/**
* {@link Map} of {@link Rule}'s id to current {@link RuleStatus} object.
*/
private Map<String, RuleStatusInfo> statusMap = new HashMap<String, RuleStatusInfo>();
protected Logger logger = LoggerFactory.getLogger(RuleEngine.class.getName());
private StatusInfoCallback statusInfoCallback;
private Map<String, Map<String, Object>> contextMap;
private ModuleTypeRegistry mtRegistry;
private CompositeModuleHandlerFactory compositeFactory;
private int ruleMaxID = 0;
private Map<String, Future> scheduleTasks = new HashMap<String, Future>(31);
private ScheduledExecutorService executor;
private Gson gson;
/**
* Constructor of {@link RuleEngine}. It initializes the logger and starts tracker for {@link ModuleHandlerFactory}
* services.
*
* @param bc {@link BundleContext} used for tracker registration and rule engine logger creation.
* @throws InvalidSyntaxException
*/
public RuleEngine() {
this.rules = new HashMap<String, RuntimeRule>(20);
this.contextMap = new HashMap<String, Map<String, Object>>();
this.moduleHandlerFactories = new HashMap<String, ModuleHandlerFactory>(20);
}
protected void setModuleTypeRegistry(ModuleTypeRegistry moduleTypeRegistry) {
if (moduleTypeRegistry == null) {
mtRegistry.removeRegistryChangeListener(this);
mtRegistry = null;
} else {
mtRegistry = moduleTypeRegistry;
mtRegistry.addRegistryChangeListener(this);
}
ConnectionValidator.setRegistry(mtRegistry);
}
protected void setCompositeModuleHandlerFactory(CompositeModuleHandlerFactory compositeFactory) {
this.compositeFactory = compositeFactory;
}
@Override
public void added(ModuleType moduleType) {
String moduleTypeName = moduleType.getUID();
for (ModuleHandlerFactory moduleHandlerFactory : allModuleHandlerFactories) {
Collection<String> moduleTypes = moduleHandlerFactory.getTypes();
if (moduleTypes.contains(moduleTypeName)) {
synchronized (this) {
this.moduleHandlerFactories.put(moduleTypeName, moduleHandlerFactory);
}
break;
}
}
Set<String> rules = null;
synchronized (this) {
Set<String> rulesPerModule = mapModuleTypeToRules.get(moduleTypeName);
if (rulesPerModule != null) {
rules = new HashSet<String>();
rules.addAll(rulesPerModule);
}
}
if (rules != null) {
for (String rUID : rules) {
RuleStatus ruleStatus = getRuleStatus(rUID);
if (ruleStatus == RuleStatus.UNINITIALIZED) {
scheduleRuleInitialization(rUID);
}
}
}
}
@Override
public void removed(ModuleType moduleType) {
// removing module types does not effect the rule
}
@Override
public void updated(ModuleType oldElement, ModuleType moduleType) {
if (moduleType.equals(oldElement)) {
return;
}
String moduleTypeName = moduleType.getUID();
Set<String> rules = null;
synchronized (this) {
Set<String> rulesPerModule = mapModuleTypeToRules.get(moduleTypeName);
if (rulesPerModule != null) {
rules = new HashSet<String>();
rules.addAll(rulesPerModule);
}
}
if (rules != null) {
for (String rUID : rules) {
if (getRuleStatus(rUID).equals(RuleStatus.IDLE) || getRuleStatus(rUID).equals(RuleStatus.RUNNING)) {
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.UNINITIALIZED), true);
unregister(getRuntimeRule(rUID));
}
if (!getRuleStatus(rUID).equals(RuleStatus.DISABLED)) {
scheduleRuleInitialization(rUID);
}
}
}
}
protected void addModuleHandlerFactory(ModuleHandlerFactory moduleHandlerFactory) {
logger.debug("ModuleHandlerFactory added.");
allModuleHandlerFactories.add(moduleHandlerFactory);
Collection<String> moduleTypes = moduleHandlerFactory.getTypes();
addNewModuleTypes(moduleHandlerFactory, moduleTypes);
}
protected void removeModuleHandlerFactory(ModuleHandlerFactory moduleHandlerFactory) {
if (moduleHandlerFactory instanceof CompositeModuleHandlerFactory) {
compositeFactory.deactivate();
compositeFactory = null;
}
allModuleHandlerFactories.remove(moduleHandlerFactory);
Collection<String> moduleTypes = moduleHandlerFactory.getTypes();
removeMissingModuleTypes(moduleTypes);
updateModuleHandlerFactoryMap(moduleTypes);
}
private synchronized void updateModuleHandlerFactoryMap(Collection<String> removedTypes) {
for (Iterator<String> it = removedTypes.iterator(); it.hasNext();) {
String moduleTypeName = it.next();
moduleHandlerFactories.remove(moduleTypeName);
}
}
/**
* This method add a new rule into rule engine. Scope identity of the Rule is the identity of the caller.
*
* @param rule a rule which has to be added.
* @param isEnabled specifies the rule to be added as disabled or not.
*/
protected void addRule(Rule rule, boolean isEnabled) {
String rUID = rule.getUID();
RuntimeRule runtimeRule = new RuntimeRule(rule);
synchronized (this) {
rules.put(rUID, runtimeRule);
if (isEnabled) {
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.UNINITIALIZED), false);
setRule(runtimeRule);
} else {
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.DISABLED), true);
}
}
}
/**
* Validates IDs of modules. The module id must not contain dot.
*
* @param modules list of trigger, condition and action modules
* @throws IllegalArgumentException when a module id contains dot.
*/
private void validateModuleIDs(List<Module> modules) {
for (Module m : modules) {
String mId = m.getId();
if (mId == null || !mId.matches("[A-Za-z0-9_-]*")) {
throw new IllegalArgumentException("Invalid module uid: " + (mId != null ? mId : "null")
+ ". It must not be null or not fit to the pattern: [A-Za-z0-9_-]*");
}
}
}
/**
* This method is used to update existing rule. It creates an internal {@link RuntimeRule} object which is deep copy
* of passed {@link Rule} object. If the rule exist in the rule engine it will be replaced by the new one.
*
* @param rule a rule which has to be updated.
* @param enabled specifies the rule to be updated as disabled or not.
*/
protected void updateRule(Rule rule, boolean isEnabled) {
String rUID = rule.getUID();
if (getRuntimeRule(rUID) == null) {
logger.debug("There is no rule with UID '{}' which could be updated", rUID);
return;
}
RuntimeRule runtimeRule = new RuntimeRule(rule);
synchronized (this) {
RuntimeRule oldRule = rules.get(rUID);
unregister(oldRule);
rules.put(rUID, runtimeRule);
if (isEnabled) {
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.UNINITIALIZED), false);
setRule(runtimeRule);
} else {
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.DISABLED), true);
}
}
logger.debug("Rule with UID '{}' is updated.", rUID);
}
/**
* This method tries to initialize the rule. It uses available {@link ModuleHandlerFactory}s to create
* {@link ModuleHandler}s for all {@link Module}s of the {@link Rule} and to link them. When all the modules have
* associated module handlers then the {@link Rule} is initialized and it is ready to working. It goes into idle
* state. Otherwise the Rule stays into not initialized and continue to wait missing handlers, module types or
* templates.
*
* @param rUID a UID of rule which tries to be initialized.
*/
private void setRule(RuntimeRule runtimeRule) {
if (isDisposed) {
return;
}
String rUID = runtimeRule.getUID();
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.INITIALIZING), true);
if (runtimeRule.getTemplateUID() != null) {
setRuleStatusInfo(rUID,
new RuleStatusInfo(RuleStatus.UNINITIALIZED, RuleStatusDetail.TEMPLATE_MISSING_ERROR), true);
return; // Template is not available (when a template is resolved it removes tempalteUID configuration
// property). The rule must stay NOT_INITIALISED.
}
List<Module> modules = runtimeRule.getModules(null);
if (modules != null) {
for (Module m : modules) {
updateMapModuleTypeToRule(rUID, m.getTypeUID());
}
}
String errMsgs;
try {
validateModuleIDs(modules);
resolveConfiguration(runtimeRule);
autoMapConnections(runtimeRule);
ConnectionValidator.validateConnections(runtimeRule);
} catch (RuntimeException e) {
errMsgs = "\n Validation of rule " + rUID + " has failed! " + e.getLocalizedMessage();
// change state to NOTINITIALIZED
setRuleStatusInfo(rUID,
new RuleStatusInfo(RuleStatus.UNINITIALIZED, RuleStatusDetail.CONFIGURATION_ERROR, errMsgs.trim()),
true);
return;
}
errMsgs = setModuleHandlers(rUID, modules);
if (errMsgs == null) {
register(runtimeRule);
// change state to IDLE
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.IDLE), true);
Future f = scheduleTasks.remove(rUID);
if (f != null) {
if (!f.isDone()) {
f.cancel(true);
}
}
if (scheduleTasks.isEmpty()) {
if (executor != null) {
executor.shutdown();
executor = null;
}
}
} else {
// change state to NOTINITIALIZED
setRuleStatusInfo(rUID,
new RuleStatusInfo(RuleStatus.UNINITIALIZED, RuleStatusDetail.HANDLER_INITIALIZING_ERROR, errMsgs),
true);
unregister(runtimeRule);
}
}
/**
* This method is used to update {@link RuleStatusInfo} of the rule. It also notifies the registry about the change.
*
* @param rUID UID of the rule which has changed status info.
* @param status new rule status info
*/
private void setRuleStatusInfo(String rUID, RuleStatusInfo status, boolean isSendEvent) {
synchronized (this) {
statusMap.put(rUID, status);
}
if (isSendEvent) {
notifyStatusInfoCallback(rUID, status);
}
}
private void notifyStatusInfoCallback(String rUID, RuleStatusInfo statusInfo) {
StatusInfoCallback statusInfoCallback = this.statusInfoCallback;
if (statusInfoCallback != null) {
try {
statusInfoCallback.statusInfoChanged(rUID, statusInfo);
} catch (Exception exc) {
logger.error("Exception while notifying StatusInfoCallback '{}' for rule '{}'", statusInfoCallback,
rUID, exc);
}
}
}
/**
* This method links modules to corresponding module handlers.
*
* @param rUID id of rule containing these modules
* @param modules list of modules
* @return null when all modules are connected or list of RuleErrors for missing handlers.
*/
private <T extends Module> String setModuleHandlers(String rUID, List<T> modules) {
StringBuffer sb = null;
if (modules != null) {
for (T m : modules) {
try {
ModuleHandler moduleHandler = getModuleHandler(m, rUID);
if (moduleHandler != null) {
if (m instanceof RuntimeAction) {
((RuntimeAction) m).setModuleHandler((ActionHandler) moduleHandler);
} else if (m instanceof RuntimeCondition) {
((RuntimeCondition) m).setModuleHandler((ConditionHandler) moduleHandler);
} else if (m instanceof RuntimeTrigger) {
((RuntimeTrigger) m).setModuleHandler((TriggerHandler) moduleHandler);
}
} else {
if (sb == null) {
sb = new StringBuffer();
}
String message = "Missing handler '" + m.getTypeUID() + "' for module '" + m.getId() + "'";
sb.append(message).append("\n");
logger.trace(message);
}
} catch (Throwable t) {
if (sb == null) {
sb = new StringBuffer();
}
String message = "Getting handler '" + m.getTypeUID() + "' for module '" + m.getId() + "' failed: "
+ t.getMessage();
sb.append(message).append("\n");
logger.trace(message);
}
}
}
return sb != null ? sb.toString() : null;
}
/**
* Gets {@link RuleEngineCallback} for passed {@link Rule}. If it does not exists, a callback object is created
*
* @param rule rule object for which the callback is looking for.
* @return a {@link RuleEngineCallback} corresponding to the passed {@link Rule} object.
*/
private synchronized RuleEngineCallbackImpl getRuleEngineCallback(RuntimeRule rule) {
RuleEngineCallbackImpl result = reCallbacks.get(rule.getUID());
if (result == null) {
result = new RuleEngineCallbackImpl(this, rule);
reCallbacks.put(rule.getUID(), result);
}
return result;
}
/**
* Unlink module handlers from their modules. The method is called when the rule containing these modules goes into
* not initialized state .
*
* @param modules list of module which are disconnected.
*/
private <T extends Module> void removeModuleHandlers(List<T> modules, String ruleUID) {
if (modules != null) {
for (T m : modules) {
ModuleHandler handler = null;
if (m instanceof RuntimeAction) {
handler = ((RuntimeAction) m).getModuleHandler();
} else if (m instanceof RuntimeCondition) {
handler = ((RuntimeCondition) m).getModuleHandler();
} else if (m instanceof RuntimeTrigger) {
handler = ((RuntimeTrigger) m).getModuleHandler();
}
if (handler != null) {
ModuleHandlerFactory factory = getModuleHandlerFactory(m.getTypeUID());
if (factory != null) {
factory.ungetHandler(m, ruleUID, handler);
}
if (m instanceof RuntimeAction) {
((RuntimeAction) m).setModuleHandler(null);
} else if (m instanceof RuntimeCondition) {
((RuntimeCondition) m).setModuleHandler(null);
} else if (m instanceof RuntimeTrigger) {
((RuntimeTrigger) m).setModuleHandler(null);
}
}
}
}
}
/**
* This method register the Rule to start working. This is the final step of initialization process where triggers
* received {@link RuleEngineCallback}s object and starts to notify the rule engine when they are triggered. After
* activating all triggers the rule goes into IDLE state
*
* @param rule an initialized rule which has to starts tracking the triggers.
*/
private void register(RuntimeRule rule) {
RuleEngineCallback reCallback = getRuleEngineCallback(rule);
for (Iterator<Trigger> it = rule.getTriggers().iterator(); it.hasNext();) {
RuntimeTrigger t = (RuntimeTrigger) it.next();
TriggerHandler triggerHandler = t.getModuleHandler();
triggerHandler.setRuleEngineCallback(reCallback);
}
}
/**
* This method unregister rule form rule engine and the rule stops working. This is happen when the {@link Rule} is
* removed or some of module handlers are disappeared. In the second case the rule stays available but its state is
* moved to not initialized.
*
* @param r the unregistered rule
*/
private void unregister(RuntimeRule r) {
if (r != null) {
synchronized (this) {
RuleEngineCallbackImpl reCallback = reCallbacks.remove(r.getUID());
if (reCallback != null) {
reCallback.dispose();
}
}
removeModuleHandlers(r.getTriggers(), r.getUID());
removeModuleHandlers(r.getActions(), r.getUID());
removeModuleHandlers(r.getConditions(), r.getUID());
}
}
/**
* Gets handler of passed module.
*
* @param m a {@link Module} which is looking for handler
* @return handler for this module or null when it is not available.
*/
private ModuleHandler getModuleHandler(Module m, String ruleUID) {
String moduleTypeId = m.getTypeUID();
ModuleHandlerFactory mhf = getModuleHandlerFactory(moduleTypeId);
if (mhf == null || mtRegistry.get(moduleTypeId) == null) {
return null;
}
return mhf.getHandler(m, ruleUID);
}
public ModuleHandlerFactory getModuleHandlerFactory(String moduleTypeId) {
ModuleHandlerFactory mhf = null;
synchronized (this) {
mhf = moduleHandlerFactories.get(moduleTypeId);
}
if (mhf == null) {
ModuleType mt = mtRegistry.get(moduleTypeId);
if (mt instanceof CompositeTriggerType || //
mt instanceof CompositeConditionType || //
mt instanceof CompositeActionType) {
mhf = compositeFactory;
}
}
return mhf;
}
public synchronized void updateMapModuleTypeToRule(String rUID, String moduleTypeId) {
Set<String> rules = mapModuleTypeToRules.get(moduleTypeId);
if (rules == null) {
rules = new HashSet<String>(11);
}
rules.add(rUID);
mapModuleTypeToRules.put(moduleTypeId, rules);
}
/**
* This method removes Rule from rule engine. It is called by the {@link RuleRegistry}
*
* @param rUID id of removed {@link Rule}
* @return true when a rule is deleted, false when there is no rule with such id.
*/
protected synchronized boolean removeRule(String rUID) {
RuntimeRule r = rules.remove(rUID);
if (r != null) {
removeRuleEntry(r);
return true;
}
return false;
}
/**
* Utility method cleaning status and handler type Maps of removing {@link Rule}.
*
* @param r removed {@link Rule}
* @return removed rule
*/
private RuntimeRule removeRuleEntry(RuntimeRule r) {
unregister(r);
synchronized (this) {
for (Iterator<Map.Entry<String, Set<String>>> it = mapModuleTypeToRules.entrySet().iterator(); it
.hasNext();) {
Map.Entry<String, Set<String>> e = it.next();
Set<String> rules = e.getValue();
if (rules != null && rules.contains(r.getUID())) {
rules.remove(r.getUID());
if (rules.size() < 1) {
it.remove();
}
}
}
statusMap.remove(r.getUID());
}
return r;
}
/**
* Gets {@link RuntimeRule} corresponding to the passed id. This method is used internally and it does not create a
* copy of the rule.
*
* @param rUID unieque id of the {@link Rule}
* @return internal {@link RuntimeRule} object
*/
protected synchronized RuntimeRule getRuntimeRule(String rUID) {
return rules.get(rUID);
}
/**
* Gets all rules available in the rule engine.
*
* @return collection of all added rules.
*/
protected synchronized Collection<RuntimeRule> getRuntimeRules() {
return Collections.unmodifiableCollection(rules.values());
}
/**
* This method can switch enabled/ disabled state of the {@link Rule}
*
* @param rUID unique id of the rule
* @param isEnabled true to enable the rule, false to disable it
*/
protected void setRuleEnabled(Rule rule, boolean isEnabled) {
String rUID = rule.getUID();
RuleStatus status = getRuleStatus(rUID);
String enabled = isEnabled ? "enabled" : "disabled";
RuntimeRule runtimeRule = getRuntimeRule(rUID);
if (runtimeRule == null) {
logger.debug("There is no rule with UID '{}' which could be {}", rUID, enabled);
return;
}
if (isEnabled) {
if (status == RuleStatus.DISABLED) {
setRule(runtimeRule);
} else {
logger.debug("The rule rId = {} is already enabled.", rUID);
}
} else {
unregister(runtimeRule);
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.DISABLED), true);
}
}
private void addNewModuleTypes(ModuleHandlerFactory mhf, Collection<String> moduleTypes) {
Set<String> notInitailizedRules = null;
for (Iterator<String> it = moduleTypes.iterator(); it.hasNext();) {
String moduleTypeName = it.next();
Set<String> rules = null;
synchronized (this) {
moduleHandlerFactories.put(moduleTypeName, mhf);
Set<String> rulesPerModule = mapModuleTypeToRules.get(moduleTypeName);
if (rulesPerModule != null) {
rules = new HashSet<String>();
rules.addAll(rulesPerModule);
}
}
if (rules != null) {
for (String rUID : rules) {
RuleStatus ruleStatus = getRuleStatus(rUID);
if (ruleStatus == RuleStatus.UNINITIALIZED) {
notInitailizedRules = notInitailizedRules != null ? notInitailizedRules
: new HashSet<String>(20);
notInitailizedRules.add(rUID);
}
}
}
}
if (notInitailizedRules != null) {
for (final String rUID : notInitailizedRules) {
scheduleRuleInitialization(rUID);
}
}
}
protected void scheduleRuleInitialization(final String rUID) {
Future f = scheduleTasks.get(rUID);
if (f == null) {
ScheduledExecutorService ex = getScheduledExecutor();
f = ex.schedule(new Runnable() {
@Override
public void run() {
setRule(getRuntimeRule(rUID));
}
}, scheduleReinitializationDelay, TimeUnit.MILLISECONDS);
scheduleTasks.put(rUID, f);
}
}
private void removeMissingModuleTypes(Collection<String> moduleTypes) {
Map<String, List<String>> mapMissingHandlers = null;
for (Iterator<String> it = moduleTypes.iterator(); it.hasNext();) {
String moduleTypeName = it.next();
Set<String> rules = null;
synchronized (this) {
rules = mapModuleTypeToRules.get(moduleTypeName);
}
if (rules != null) {
for (String rUID : rules) {
RuleStatus ruleStatus = getRuleStatus(rUID);
switch (ruleStatus) {
case RUNNING:
case IDLE:
mapMissingHandlers = mapMissingHandlers != null ? mapMissingHandlers
: new HashMap<String, List<String>>(20);
List<String> list = mapMissingHandlers.get(rUID);
if (list == null) {
list = new ArrayList<String>(5);
}
list.add(moduleTypeName);
mapMissingHandlers.put(rUID, list);
break;
default:
break;
}
}
}
} // for
if (mapMissingHandlers != null) {
for (Entry<String, List<String>> e : mapMissingHandlers.entrySet()) {
String rUID = e.getKey();
List<String> missingTypes = e.getValue();
StringBuffer sb = new StringBuffer();
sb.append("Missing handlers: ");
for (String typeUID : missingTypes) {
sb.append(typeUID).append(", ");
}
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.UNINITIALIZED,
RuleStatusDetail.HANDLER_MISSING_ERROR, sb.substring(0, sb.length() - 2)), true);
unregister(getRuntimeRule(rUID));
}
}
}
/**
* This method runs a {@link Rule}. It is called by the {@link RuleEngineCallback}'s thread when a new
* {@link TriggerData} is available. This method switches
*
* @param rule the {@link Rule} which has to evaluate new {@link TriggerData}.
* @param td {@link TriggerData} object containing new values for {@link Trigger}'s {@link Output}s
*/
protected void runRule(RuntimeRule rule, RuleEngineCallbackImpl.TriggerData td) {
String rUID = rule.getUID();
if (reCallbacks.get(rUID) == null) {
// the rule was unregistered
return;
}
synchronized (this) {
final RuleStatus ruleStatus = getRuleStatus(rUID);
if (ruleStatus != RuleStatus.IDLE) {
logger.error("Failed to execute rule ‘{}' with status '{}'", rUID, ruleStatus.name());
return;
}
// change state to RUNNING
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.RUNNING), true);
}
try {
clearContext(rule);
setTriggerOutputs(rUID, td);
boolean isSatisfied = calculateConditions(rule);
if (isSatisfied) {
executeActions(rule, true);
logger.debug("The rule '{}' is executed.", rUID);
} else {
logger.debug("The rule '{}' is NOT executed, since it has unsatisfied conditions.", rUID);
}
} catch (Throwable t) {
logger.error("Failed to execute rule '{}': {}", rUID, t.getMessage());
logger.debug("", t);
}
// change state to IDLE only if the rule has not been DISABLED.
synchronized (this) {
if (getRuleStatus(rUID) == RuleStatus.RUNNING) {
setRuleStatusInfo(rUID, new RuleStatusInfo(RuleStatus.IDLE), true);
}
}
}
protected void runNow(String ruleUID, boolean considerConditions, Map<String, Object> context) {
RuntimeRule rule = getRuntimeRule(ruleUID);
if (rule == null) {
logger.warn("Failed to execute rule '{}': Invalid Rule UID", ruleUID);
return;
}
synchronized (this) {
final RuleStatus ruleStatus = getRuleStatus(ruleUID);
if (ruleStatus != RuleStatus.IDLE) {
logger.error("Failed to execute rule ‘{}' with status '{}'", ruleUID, ruleStatus.name());
return;
}
// change state to RUNNING
setRuleStatusInfo(ruleUID, new RuleStatusInfo(RuleStatus.RUNNING), true);
}
try {
clearContext(rule);
if (context != null && !context.isEmpty()) {
getContext(ruleUID).putAll(context);
}
if (considerConditions) {
if (calculateConditions(rule)) {
executeActions(rule, false);
}
} else {
executeActions(rule, false);
}
logger.debug("The rule '{}' is executed.", ruleUID);
} catch (Throwable t) {
logger.error("Fail to execute rule '{}': {}", new Object[] { ruleUID, t.getMessage() }, t);
}
// change state to IDLE only if the rule has not been DISABLED.
synchronized (this) {
if (getRuleStatus(ruleUID) == RuleStatus.RUNNING) {
setRuleStatusInfo(ruleUID, new RuleStatusInfo(RuleStatus.IDLE), true);
}
}
}
protected void runNow(String ruleUID) {
runNow(ruleUID, false, null);
}
protected void clearContext(RuntimeRule rule) {
Map<String, Object> context = contextMap.get(rule.getUID());
if (context != null) {
context.clear();
}
}
/**
* The method updates {@link Output} of the {@link Trigger} with a new triggered data.
*
* @param td new Triggered data.
*/
private void setTriggerOutputs(String ruleUID, TriggerData td) {
Trigger t = td.getTrigger();
updateContext(ruleUID, t.getId(), td.getOutputs());
}
/**
* Updates current context of rule engine.
*
* @param moduleUID uid of updated module.
*
* @param outputs new output values.
*/
private void updateContext(String ruleUID, String moduleUID, Map<String, ?> outputs) {
Map<String, Object> context = getContext(ruleUID);
if (outputs != null) {
for (Map.Entry<String, ?> entry : outputs.entrySet()) {
String key = moduleUID + OUTPUT_SEPARATOR + entry.getKey();
context.put(key, entry.getValue());
}
}
}
/**
* @return copy of current context in rule engine
*/
private Map<String, Object> getContext(String ruleUID) {
return getContext(ruleUID, null);
}
private Map<String, Object> getContext(String ruleUID, Set<Connection> connections) {
Map<String, Object> context = contextMap.get(ruleUID);
if (context == null) {
context = new HashMap<String, Object>();
contextMap.put(ruleUID, context);
}
if (connections != null) {
StringBuffer sb = new StringBuffer();
for (Connection c : connections) {
String outputModuleId = c.getOuputModuleId();
if (outputModuleId != null) {
sb.append(outputModuleId).append(OUTPUT_SEPARATOR).append(c.getOutputName());
context.put(c.getInputName(), context.get(sb.toString()));
sb.setLength(0);
} else {
// get reference from context
String ref = c.getOutputName();
final Object value = ReferenceResolverUtil.resolveReference(ref, context);
if (value != null) {
context.put(c.getInputName(), value);
}
}
}
}
return context;
}
/**
* This method checks if all rule's condition are satisfied or not.
*
* @param rule the checked rule
* @return true when all conditions of the rule are satisfied, false otherwise.
*/
private boolean calculateConditions(Rule rule) {
List<Condition> conditions = ((RuntimeRule) rule).getConditions();
if (conditions.size() == 0) {
return true;
}
RuleStatus ruleStatus = null;
for (Iterator<Condition> it = conditions.iterator(); it.hasNext();) {
ruleStatus = getRuleStatus(rule.getUID());
if (ruleStatus != RuleStatus.RUNNING) {
return false;
}
RuntimeCondition c = (RuntimeCondition) it.next();
ConditionHandler tHandler = c.getModuleHandler();
Map<String, Object> context = getContext(rule.getUID(), c.getConnections());
if (!tHandler.isSatisfied(Collections.unmodifiableMap(context))) {
logger.debug("The condition '{}' of rule '{}' is unsatisfied.",
new Object[] { c.getId(), rule.getUID() });
return false;
}
}
return true;
}
/**
* This method evaluates actions of the {@link Rule} and set their {@link Output}s when they exists.
*
* @param rule executed rule.
*/
private void executeActions(Rule rule, boolean stopOnFirstFail) {
List<Action> actions = ((RuntimeRule) rule).getActions();
if (actions == null || actions.size() == 0) {
return;
}
RuleStatus ruleStatus = null;
RuntimeAction action = null;