818cae802b3247cd4667cdb0324c1b63a720d4b3
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.drools.controller.internal;
22
23 import com.fasterxml.jackson.annotation.JsonIgnore;
24 import com.fasterxml.jackson.annotation.JsonProperty;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Objects;
31 import java.util.stream.Collectors;
32 import org.apache.commons.collections4.queue.CircularFifoQueue;
33 import org.checkerframework.checker.nullness.qual.NonNull;
34 import org.drools.core.ClassObjectFilter;
35 import org.kie.api.definition.KiePackage;
36 import org.kie.api.definition.rule.Query;
37 import org.kie.api.runtime.KieSession;
38 import org.kie.api.runtime.rule.FactHandle;
39 import org.kie.api.runtime.rule.QueryResults;
40 import org.kie.api.runtime.rule.QueryResultsRow;
41 import org.onap.policy.common.endpoints.event.comm.TopicSink;
42 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
43 import org.onap.policy.common.gson.annotation.GsonJsonProperty;
44 import org.onap.policy.drools.controller.DroolsController;
45 import org.onap.policy.drools.core.PolicyContainer;
46 import org.onap.policy.drools.core.PolicySession;
47 import org.onap.policy.drools.core.jmx.PdpJmx;
48 import org.onap.policy.drools.features.DroolsControllerFeatureApi;
49 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
50 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
51 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
52 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration;
53 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder;
54 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.PotentialCoderFilter;
55 import org.onap.policy.drools.utils.ReflectionUtil;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * Maven-based Drools Controller that interacts with the
61  * policy-core PolicyContainer and PolicySession to manage
62  * Drools containers instantiated using Maven.
63  */
64 public class MavenDroolsController implements DroolsController {
65
66     /**
67      * logger.
68      */
69     private static Logger  logger = LoggerFactory.getLogger(MavenDroolsController.class);
70
71     /**
72      * Policy Container, the access object to the policy-core layer.
73      */
74     @JsonIgnore
75     @GsonJsonIgnore
76     protected final PolicyContainer policyContainer;
77
78     /**
79      * alive status of this drools controller,
80      * reflects invocation of start()/stop() only.
81      */
82     protected volatile boolean alive = false;
83
84     /**
85      * locked status of this drools controller,
86      * reflects if i/o drools related operations are permitted,
87      * more specifically: offer() and deliver().
88      * It does not affect the ability to start and stop
89      * underlying drools infrastructure
90      */
91     protected volatile boolean locked = false;
92
93     /**
94      * list of topics, each with associated decoder classes, each
95      * with a list of associated filters.
96      */
97     protected List<TopicCoderFilterConfiguration> decoderConfigurations;
98
99     /**
100      * list of topics, each with associated encoder classes, each
101      * with a list of associated filters.
102      */
103     protected List<TopicCoderFilterConfiguration> encoderConfigurations;
104
105     /**
106      * recent source events processed.
107      */
108     protected final CircularFifoQueue<Object> recentSourceEvents = new CircularFifoQueue<>(10);
109
110     /**
111      * recent sink events processed.
112      */
113     protected final CircularFifoQueue<String> recentSinkEvents = new CircularFifoQueue<>(10);
114
115     /**
116      * original Drools Model/Rules classloader hash.
117      */
118     protected int modelClassLoaderHash;
119
120     /**
121      * Expanded version of the constructor.
122      *
123      * @param groupId maven group id
124      * @param artifactId maven artifact id
125      * @param version maven version
126      * @param decoderConfigurations list of topic -> decoders -> filters mapping
127      * @param encoderConfigurations list of topic -> encoders -> filters mapping
128      *
129      * @throws IllegalArgumentException invalid arguments passed in
130      */
131     public MavenDroolsController(String groupId,
132             String artifactId,
133             String version,
134             List<TopicCoderFilterConfiguration> decoderConfigurations,
135             List<TopicCoderFilterConfiguration> encoderConfigurations) {
136
137         logger.info("drools-controller instantiation [{}:{}:{}]", groupId, artifactId, version);
138
139         if (groupId == null || groupId.isEmpty()) {
140             throw new IllegalArgumentException("Missing maven group-id coordinate");
141         }
142
143         if (artifactId == null || artifactId.isEmpty()) {
144             throw new IllegalArgumentException("Missing maven artifact-id coordinate");
145         }
146
147         if (version == null || version.isEmpty()) {
148             throw new IllegalArgumentException("Missing maven version coordinate");
149         }
150
151         this.policyContainer = new PolicyContainer(groupId, artifactId, version);
152         this.init(decoderConfigurations, encoderConfigurations);
153
154         logger.debug("{}: instantiation completed ", this);
155     }
156
157     /**
158      * init encoding/decoding configuration.
159      *
160      * @param decoderConfigurations list of topic -> decoders -> filters mapping
161      * @param encoderConfigurations list of topic -> encoders -> filters mapping
162      */
163     protected void init(List<TopicCoderFilterConfiguration> decoderConfigurations,
164             List<TopicCoderFilterConfiguration> encoderConfigurations) {
165
166         this.decoderConfigurations = decoderConfigurations;
167         this.encoderConfigurations = encoderConfigurations;
168
169         this.initCoders(decoderConfigurations, true);
170         this.initCoders(encoderConfigurations, false);
171
172         this.modelClassLoaderHash = this.policyContainer.getClassLoader().hashCode();
173     }
174
175     @Override
176     public void updateToVersion(String newGroupId, String newArtifactId, String newVersion,
177             List<TopicCoderFilterConfiguration> decoderConfigurations,
178             List<TopicCoderFilterConfiguration> encoderConfigurations)
179                     throws LinkageError {
180
181         logger.info("updating version -> [{}:{}:{}]", newGroupId, newArtifactId, newVersion);
182
183         if (newGroupId == null || newGroupId.isEmpty()) {
184             throw new IllegalArgumentException("Missing maven group-id coordinate");
185         }
186
187         if (newArtifactId == null || newArtifactId.isEmpty()) {
188             throw new IllegalArgumentException("Missing maven artifact-id coordinate");
189         }
190
191         if (newVersion == null || newVersion.isEmpty()) {
192             throw new IllegalArgumentException("Missing maven version coordinate");
193         }
194
195         if (newGroupId.equalsIgnoreCase(DroolsController.NO_GROUP_ID)
196                 || newArtifactId.equalsIgnoreCase(DroolsController.NO_ARTIFACT_ID)
197                 || newVersion.equalsIgnoreCase(DroolsController.NO_VERSION)) {
198             throw new IllegalArgumentException("BRAINLESS maven coordinates provided: "
199                     + newGroupId + ":" + newArtifactId + ":"
200                     + newVersion);
201         }
202
203         if (newGroupId.equalsIgnoreCase(this.getGroupId())
204                 && newArtifactId.equalsIgnoreCase(this.getArtifactId())
205                 && newVersion.equalsIgnoreCase(this.getVersion())) {
206             logger.warn("Al in the right version: " + newGroupId + ":"
207                     + newArtifactId + ":" +  newVersion + " vs. " + this);
208             return;
209         }
210
211         if (!newGroupId.equalsIgnoreCase(this.getGroupId())
212                 || !newArtifactId.equalsIgnoreCase(this.getArtifactId())) {
213             throw new IllegalArgumentException(
214                     "Group ID and Artifact ID maven coordinates must be identical for the upgrade: "
215                     + newGroupId + ":" + newArtifactId + ":"
216                     + newVersion + " vs. " + this);
217         }
218
219         /* upgrade */
220         String messages = this.policyContainer.updateToVersion(newVersion);
221         logger.warn("{} UPGRADE results: {}", this, messages);
222
223         /*
224          * If all sucessful (can load new container), now we can remove all coders from previous sessions
225          */
226         this.removeCoders();
227
228         /*
229          * add the new coders
230          */
231         this.init(decoderConfigurations, encoderConfigurations);
232
233         logger.info("UPDATE-TO-VERSION: completed {}", this);
234     }
235
236     /**
237      * initialize decoders for all the topics supported by this controller
238      * Note this is critical to be done after the Policy Container is
239      * instantiated to be able to fetch the corresponding classes.
240      *
241      * @param coderConfigurations list of topic -> decoders -> filters mapping
242      */
243     protected void initCoders(List<TopicCoderFilterConfiguration> coderConfigurations,
244             boolean decoder) {
245
246         logger.info("INIT-CODERS: {}", this);
247
248         if (coderConfigurations == null) {
249             return;
250         }
251
252
253         for (TopicCoderFilterConfiguration coderConfig: coderConfigurations) {
254             String topic = coderConfig.getTopic();
255
256             CustomGsonCoder customGsonCoder = coderConfig.getCustomGsonCoder();
257             if (coderConfig.getCustomGsonCoder() != null
258                     && coderConfig.getCustomGsonCoder().getClassContainer() != null
259                     && !coderConfig.getCustomGsonCoder().getClassContainer().isEmpty()) {
260
261                 String customGsonCoderClass = coderConfig.getCustomGsonCoder().getClassContainer();
262                 if (!ReflectionUtil.isClass(this.policyContainer.getClassLoader(),
263                         customGsonCoderClass)) {
264                     throw makeRetrieveEx(customGsonCoderClass);
265                 } else {
266                     if (logger.isInfoEnabled()) {
267                         logClassFetched(customGsonCoderClass);
268                     }
269                 }
270             }
271
272             List<PotentialCoderFilter> coderFilters = coderConfig.getCoderFilters();
273             if (coderFilters == null || coderFilters.isEmpty()) {
274                 continue;
275             }
276
277             for (PotentialCoderFilter coderFilter : coderFilters) {
278                 String potentialCodedClass = coderFilter.getCodedClass();
279                 JsonProtocolFilter protocolFilter = coderFilter.getFilter();
280
281                 if (!ReflectionUtil.isClass(this.policyContainer.getClassLoader(),
282                         potentialCodedClass)) {
283                     throw makeRetrieveEx(potentialCodedClass);
284                 } else {
285                     if (logger.isInfoEnabled()) {
286                         logClassFetched(potentialCodedClass);
287                     }
288                 }
289
290                 if (decoder) {
291                     EventProtocolCoder.manager.addDecoder(EventProtocolParams.builder()
292                             .groupId(this.getGroupId())
293                             .artifactId(this.getArtifactId())
294                             .topic(topic)
295                             .eventClass(potentialCodedClass)
296                             .protocolFilter(protocolFilter)
297                             .customGsonCoder(customGsonCoder)
298                             .modelClassLoaderHash(this.policyContainer.getClassLoader().hashCode()));
299                 } else {
300                     EventProtocolCoder.manager.addEncoder(
301                             EventProtocolParams.builder().groupId(this.getGroupId())
302                                     .artifactId(this.getArtifactId()).topic(topic)
303                                     .eventClass(potentialCodedClass).protocolFilter(protocolFilter)
304                                     .customGsonCoder(customGsonCoder)
305                                     .modelClassLoaderHash(this.policyContainer.getClassLoader().hashCode()));
306                 }
307             }
308         }
309     }
310
311     /**
312      * Logs an error and makes an exception for an item that cannot be retrieved.
313      * @param itemName the item to retrieve
314      * @return a new exception
315      */
316     private IllegalArgumentException makeRetrieveEx(String itemName) {
317         logger.error("{} cannot be retrieved", itemName);
318         return new IllegalArgumentException(itemName + " cannot be retrieved");
319     }
320
321     /**
322      * Logs the name of the class that was fetched.
323      * @param className class name fetched
324      */
325     private void logClassFetched(String className) {
326         logger.info("CLASS FETCHED {}", className);
327     }
328
329
330     /**
331      * remove decoders.
332      */
333     protected void removeDecoders() {
334         logger.info("REMOVE-DECODERS: {}", this);
335
336         if (this.decoderConfigurations == null) {
337             return;
338         }
339
340
341         for (TopicCoderFilterConfiguration coderConfig: decoderConfigurations) {
342             String topic = coderConfig.getTopic();
343             EventProtocolCoder.manager.removeDecoders(this.getGroupId(), this.getArtifactId(), topic);
344         }
345     }
346
347     /**
348      * remove decoders.
349      */
350     protected void removeEncoders() {
351
352         logger.info("REMOVE-ENCODERS: {}", this);
353
354         if (this.encoderConfigurations == null) {
355             return;
356         }
357
358         for (TopicCoderFilterConfiguration coderConfig: encoderConfigurations) {
359             String topic = coderConfig.getTopic();
360             EventProtocolCoder.manager.removeEncoders(this.getGroupId(), this.getArtifactId(), topic);
361         }
362     }
363
364
365     @Override
366     public boolean ownsCoder(Class<? extends Object> coderClass, int modelHash) {
367         if (!ReflectionUtil.isClass(this.policyContainer.getClassLoader(), coderClass.getName())) {
368             logger.error("{}{} cannot be retrieved. ", this, coderClass.getName());
369             return false;
370         }
371
372         if (modelHash == this.modelClassLoaderHash) {
373             logger.info("{}{} class loader matches original drools controller rules classloader {}",
374                             coderClass.getName(), this, coderClass.getClassLoader());
375             return true;
376         } else {
377             logger.warn("{}{} class loaders don't match {} vs {}", this, coderClass.getName(),
378                             coderClass.getClassLoader(), this.policyContainer.getClassLoader());
379             return false;
380         }
381     }
382
383     @Override
384     public boolean start() {
385
386         logger.info("START: {}", this);
387
388         synchronized (this) {
389             if (this.alive) {
390                 return true;
391             }
392             this.alive = true;
393         }
394
395         return this.policyContainer.start();
396     }
397
398     @Override
399     public boolean stop() {
400
401         logger.info("STOP: {}", this);
402
403         synchronized (this) {
404             if (!this.alive) {
405                 return true;
406             }
407             this.alive = false;
408         }
409
410         return this.policyContainer.stop();
411     }
412
413     @Override
414     public void shutdown() {
415         logger.info("{}: SHUTDOWN", this);
416
417         try {
418             this.stop();
419             this.removeCoders();
420         } catch (Exception e) {
421             logger.error("{} SHUTDOWN FAILED because of {}", this, e.getMessage(), e);
422         } finally {
423             this.policyContainer.shutdown();
424         }
425
426     }
427
428     @Override
429     public void halt() {
430         logger.info("{}: HALT", this);
431
432         try {
433             this.stop();
434             this.removeCoders();
435         } catch (Exception e) {
436             logger.error("{} HALT FAILED because of {}", this, e.getMessage(), e);
437         } finally {
438             this.policyContainer.destroy();
439         }
440     }
441
442     /**
443      * removes this drools controllers and encoders and decoders from operation.
444      */
445     protected void removeCoders() {
446         logger.info("{}: REMOVE-CODERS", this);
447
448         try {
449             this.removeDecoders();
450         } catch (IllegalArgumentException e) {
451             logger.error("{} REMOVE-DECODERS FAILED because of {}", this, e.getMessage(), e);
452         }
453
454         try {
455             this.removeEncoders();
456         } catch (IllegalArgumentException e) {
457             logger.error("{} REMOVE-ENCODERS FAILED because of {}", this, e.getMessage(), e);
458         }
459     }
460
461     @Override
462     public boolean isAlive() {
463         return this.alive;
464     }
465
466     @Override
467     public boolean offer(String topic, String event) {
468         logger.debug("{}: OFFER raw event from {}", this, topic);
469
470         if (this.locked || !this.alive || this.policyContainer.getPolicySessions().isEmpty()) {
471             return true;
472         }
473
474         // 1. Now, check if this topic has a decoder:
475
476         if (!EventProtocolCoder.manager.isDecodingSupported(this.getGroupId(),
477                 this.getArtifactId(),
478                 topic)) {
479
480             logger.warn("{}: DECODING-UNSUPPORTED {}:{}:{}", this,
481                     topic, this.getGroupId(), this.getArtifactId());
482             return true;
483         }
484
485         // 2. Decode
486
487         Object anEvent;
488         try {
489             anEvent = EventProtocolCoder.manager.decode(this.getGroupId(),
490                     this.getArtifactId(),
491                     topic,
492                     event);
493         } catch (UnsupportedOperationException uoe) {
494             logger.debug("{}: DECODE FAILED: {} <- {} because of {}", this, topic,
495                     event, uoe.getMessage(), uoe);
496             return true;
497         } catch (Exception e) {
498             logger.warn("{}: DECODE FAILED: {} <- {} because of {}", this, topic,
499                     event, e.getMessage(), e);
500             return true;
501         }
502
503         return offer(anEvent);
504
505     }
506
507     @Override
508     public <T> boolean offer(T event) {
509         logger.debug("{}: OFFER event", this);
510
511         if (this.locked || !this.alive || this.policyContainer.getPolicySessions().isEmpty()) {
512             return true;
513         }
514
515         synchronized (this.recentSourceEvents) {
516             this.recentSourceEvents.add(event);
517         }
518
519         PdpJmx.getInstance().updateOccured();
520
521         // Broadcast
522
523         for (DroolsControllerFeatureApi feature : DroolsControllerFeatureApi.providers.getList()) {
524             try {
525                 if (feature.beforeInsert(this, event)) {
526                     return true;
527                 }
528             } catch (Exception e) {
529                 logger.error("{}: feature {} before-insert failure because of {}",
530                     this, feature.getClass().getName(), e.getMessage(), e);
531             }
532         }
533
534         boolean successInject = this.policyContainer.insertAll(event);
535         if (!successInject) {
536             logger.warn(this + "Failed to inject into PolicyContainer {}", this.getSessionNames());
537         }
538
539         for (DroolsControllerFeatureApi feature : DroolsControllerFeatureApi.providers.getList()) {
540             try {
541                 if (feature.afterInsert(this, event, successInject)) {
542                     return true;
543                 }
544             } catch (Exception e) {
545                 logger.error("{}: feature {} after-insert failure because of {}",
546                     this, feature.getClass().getName(), e.getMessage(), e);
547             }
548         }
549
550         return true;
551
552     }
553
554     @Override
555     public boolean deliver(TopicSink sink, Object event) {
556
557         logger.info("{}DELIVER: {} FROM {} TO {}", this, event, this, sink);
558
559         for (DroolsControllerFeatureApi feature : DroolsControllerFeatureApi.providers.getList()) {
560             try {
561                 if (feature.beforeDeliver(this, sink, event)) {
562                     return true;
563                 }
564             }
565             catch (Exception e) {
566                 logger.error("{}: feature {} before-deliver failure because of {}", this, feature.getClass().getName(),
567                         e.getMessage(), e);
568             }
569         }
570
571         if (sink == null) {
572             throw new IllegalArgumentException(this +  " invalid sink");
573         }
574
575         if (event == null) {
576             throw new IllegalArgumentException(this +  " invalid event");
577         }
578
579         if (this.locked) {
580             throw new IllegalStateException(this +  " is locked");
581         }
582
583         if (!this.alive) {
584             throw new IllegalStateException(this +  " is stopped");
585         }
586
587         String json =
588                 EventProtocolCoder.manager.encode(sink.getTopic(), event, this);
589
590         synchronized (this.recentSinkEvents) {
591             this.recentSinkEvents.add(json);
592         }
593
594         boolean success = sink.send(json);
595
596         for (DroolsControllerFeatureApi feature : DroolsControllerFeatureApi.providers.getList()) {
597             try {
598                 if (feature.afterDeliver(this, sink, event, json, success)) {
599                     return true;
600                 }
601             }
602             catch (Exception e) {
603                 logger.error("{}: feature {} after-deliver failure because of {}", this, feature.getClass().getName(),
604                         e.getMessage(), e);
605             }
606         }
607
608         return success;
609
610     }
611
612     @Override
613     public String getVersion() {
614         return this.policyContainer.getVersion();
615     }
616
617     @Override
618     public String getArtifactId() {
619         return this.policyContainer.getArtifactId();
620     }
621
622     @Override
623     public String getGroupId() {
624         return this.policyContainer.getGroupId();
625     }
626
627     /**
628      * Get model class loader hash.
629      *
630      * @return the modelClassLoaderHash
631      */
632     public int getModelClassLoaderHash() {
633         return modelClassLoaderHash;
634     }
635
636     @Override
637     public synchronized boolean lock() {
638         logger.info("LOCK: {}",  this);
639
640         this.locked = true;
641         return true;
642     }
643
644     @Override
645     public synchronized boolean unlock() {
646         logger.info("UNLOCK: {}",  this);
647
648         this.locked = false;
649         return true;
650     }
651
652     @Override
653     public boolean isLocked() {
654         return this.locked;
655     }
656
657     @JsonIgnore
658     @GsonJsonIgnore
659     @Override
660     public PolicyContainer getContainer() {
661         return this.policyContainer;
662     }
663
664     @JsonProperty("sessions")
665     @GsonJsonProperty("sessions")
666     @Override
667     public List<String> getSessionNames() {
668         return getSessionNames(true);
669     }
670
671     /**
672      * get session names.
673      *
674      * @param abbreviated true for the short form, otherwise the long form
675      * @return session names
676      */
677     protected List<String> getSessionNames(boolean abbreviated) {
678         List<String> sessionNames = new ArrayList<>();
679         try {
680             for (PolicySession session: this.policyContainer.getPolicySessions()) {
681                 if (abbreviated) {
682                     sessionNames.add(session.getName());
683                 } else {
684                     sessionNames.add(session.getFullName());
685                 }
686             }
687         } catch (Exception e) {
688             logger.warn("Can't retrieve CORE sessions: " + e.getMessage(), e);
689             sessionNames.add(e.getMessage());
690         }
691         return sessionNames;
692     }
693
694     @JsonProperty("sessionCoordinates")
695     @GsonJsonProperty("sessionCoordinates")
696     @Override
697     public List<String> getCanonicalSessionNames() {
698         return getSessionNames(false);
699     }
700
701     @Override
702     public List<String> getBaseDomainNames() {
703         return new ArrayList<>(this.policyContainer.getKieContainer().getKieBaseNames());
704     }
705
706     /**
707      * provides the underlying core layer container sessions.
708      *
709      * @return the attached Policy Container
710      */
711     protected List<PolicySession> getSessions() {
712         List<PolicySession> sessions = new ArrayList<>();
713         sessions.addAll(this.policyContainer.getPolicySessions());
714         return sessions;
715     }
716
717     /**
718      * provides the underlying core layer container session with name sessionName.
719      *
720      * @param sessionName session name
721      * @return the attached Policy Container
722      * @throws IllegalArgumentException when an invalid session name is provided
723      * @throws IllegalStateException when the drools controller is in an invalid state
724      */
725     protected PolicySession getSession(String sessionName) {
726         if (sessionName == null || sessionName.isEmpty()) {
727             throw new IllegalArgumentException("A Session Name must be provided");
728         }
729
730         List<PolicySession> sessions = this.getSessions();
731         for (PolicySession session : sessions) {
732             if (sessionName.equals(session.getName()) || sessionName.equals(session.getFullName())) {
733                 return session;
734             }
735         }
736
737         throw invalidSessNameEx(sessionName);
738     }
739
740     private IllegalArgumentException invalidSessNameEx(String sessionName) {
741         return new IllegalArgumentException("Invalid Session Name: " + sessionName);
742     }
743
744     @Override
745     public Map<String,Integer> factClassNames(String sessionName) {
746         if (sessionName == null || sessionName.isEmpty()) {
747             throw invalidSessNameEx(sessionName);
748         }
749
750         Map<String,Integer> classNames = new HashMap<>();
751
752         PolicySession session = getSession(sessionName);
753         KieSession kieSession = session.getKieSession();
754
755         Collection<FactHandle> facts = session.getKieSession().getFactHandles();
756         for (FactHandle fact : facts) {
757             try {
758                 String className = kieSession.getObject(fact).getClass().getName();
759                 if (classNames.containsKey(className)) {
760                     classNames.put(className, classNames.get(className) + 1);
761                 } else {
762                     classNames.put(className, 1);
763                 }
764             } catch (Exception e) {
765                 logger.warn("Object cannot be retrieved from fact {}", fact, e);
766             }
767         }
768
769         return classNames;
770     }
771
772     @Override
773     public long factCount(String sessionName) {
774         if (sessionName == null || sessionName.isEmpty()) {
775             throw invalidSessNameEx(sessionName);
776         }
777
778         PolicySession session = getSession(sessionName);
779         return session.getKieSession().getFactCount();
780     }
781
782     @Override
783     public List<Object> facts(String sessionName, String className, boolean delete) {
784         if (sessionName == null || sessionName.isEmpty()) {
785             throw invalidSessNameEx(sessionName);
786         }
787
788         if (className == null || className.isEmpty()) {
789             throw new IllegalArgumentException("Invalid Class Name: " + className);
790         }
791
792         Class<?> factClass =
793                 ReflectionUtil.fetchClass(this.policyContainer.getClassLoader(), className);
794         if (factClass == null) {
795             throw new IllegalArgumentException("Class cannot be fetched in model's classloader: " + className);
796         }
797
798         PolicySession session = getSession(sessionName);
799         KieSession kieSession = session.getKieSession();
800
801         List<Object> factObjects = new ArrayList<>();
802
803         Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(factClass));
804         for (FactHandle factHandle : factHandles) {
805             try {
806                 factObjects.add(kieSession.getObject(factHandle));
807                 if (delete) {
808                     kieSession.delete(factHandle);
809                 }
810             } catch (Exception e) {
811                 logger.warn("Object cannot be retrieved from fact {}", factHandle, e);
812             }
813         }
814
815         return factObjects;
816     }
817
818     @Override
819     public <T> List<T> facts(@NonNull String sessionName, @NonNull Class<T> clazz) {
820         return facts(sessionName, clazz.getName(), false)
821             .stream()
822             .filter(clazz::isInstance)
823             .map(clazz::cast)
824             .collect(Collectors.toList());
825     }
826
827     @Override
828     public List<Object> factQuery(String sessionName, String queryName, String queriedEntity,
829             boolean delete, Object... queryParams) {
830         if (sessionName == null || sessionName.isEmpty()) {
831             throw invalidSessNameEx(sessionName);
832         }
833
834         if (queryName == null || queryName.isEmpty()) {
835             throw new IllegalArgumentException("Invalid Query Name: " + queryName);
836         }
837
838         if (queriedEntity == null || queriedEntity.isEmpty()) {
839             throw new IllegalArgumentException("Invalid Queried Entity: " + queriedEntity);
840         }
841
842         PolicySession session = getSession(sessionName);
843         KieSession kieSession = session.getKieSession();
844
845         boolean found = false;
846         for (KiePackage kiePackage : kieSession.getKieBase().getKiePackages()) {
847             for (Query q : kiePackage.getQueries()) {
848                 if (q.getName() != null && q.getName().equals(queryName)) {
849                     found = true;
850                     break;
851                 }
852             }
853         }
854         if (!found) {
855             throw new IllegalArgumentException("Invalid Query Name: " + queryName);
856         }
857
858         List<Object> factObjects = new ArrayList<>();
859
860         QueryResults queryResults = kieSession.getQueryResults(queryName, queryParams);
861         for (QueryResultsRow row : queryResults) {
862             try {
863                 factObjects.add(row.get(queriedEntity));
864                 if (delete) {
865                     kieSession.delete(row.getFactHandle(queriedEntity));
866                 }
867             } catch (Exception e) {
868                 logger.warn("Object cannot be retrieved from row: {}", row, e);
869             }
870         }
871
872         return factObjects;
873     }
874
875     @Override
876     public <T> boolean delete(@NonNull String sessionName, @NonNull T fact) {
877         String factClassName = fact.getClass().getName();
878
879         PolicySession session = getSession(sessionName);
880         KieSession kieSession = session.getKieSession();
881
882         Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(fact.getClass()));
883         for (FactHandle factHandle : factHandles) {
884             try {
885                 if (Objects.equals(fact, kieSession.getObject(factHandle))) {
886                     logger.info("Deleting {} from {}", factClassName, sessionName);
887                     kieSession.delete(factHandle);
888                     return true;
889                 }
890             } catch (Exception e) {
891                 logger.warn("Object cannot be retrieved from fact {}", factHandle, e);
892             }
893         }
894         return false;
895     }
896
897     @Override
898     public <T> boolean delete(@NonNull T fact) {
899         return this.getSessionNames().stream().map((ss) -> delete(ss, fact)).reduce(false, Boolean::logicalOr);
900     }
901
902     @Override
903     public <T> boolean delete(@NonNull String sessionName, @NonNull Class<T> fact) {
904         PolicySession session = getSession(sessionName);
905         KieSession kieSession = session.getKieSession();
906
907         boolean success = true;
908         Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(fact));
909         for (FactHandle factHandle : factHandles) {
910             try {
911                 kieSession.delete(factHandle);
912             } catch (Exception e) {
913                 logger.warn("Object cannot be retrieved from fact {}", factHandle, e);
914                 success = false;
915             }
916         }
917         return success;
918     }
919
920     @Override
921     public <T> boolean delete(@NonNull Class<T> fact) {
922         return this.getSessionNames().stream().map((ss) -> delete(ss, fact)).reduce(false, Boolean::logicalOr);
923     }
924
925
926     @Override
927     public Class<?> fetchModelClass(String className) {
928         return ReflectionUtil.fetchClass(this.policyContainer.getClassLoader(), className);
929     }
930
931     /**
932      * Get recent source events.
933      *
934      * @return the recentSourceEvents
935      */
936     @Override
937     public Object[] getRecentSourceEvents() {
938         synchronized (this.recentSourceEvents) {
939             Object[] events = new Object[recentSourceEvents.size()];
940             return recentSourceEvents.toArray(events);
941         }
942     }
943
944     /**
945      * Get recent sink events.
946      *
947      * @return the recentSinkEvents
948      */
949     @Override
950     public String[] getRecentSinkEvents() {
951         synchronized (this.recentSinkEvents) {
952             String[] events = new String[recentSinkEvents.size()];
953             return recentSinkEvents.toArray(events);
954         }
955     }
956
957     @Override
958     public boolean isBrained() {
959         return true;
960     }
961
962
963     @Override
964     public String toString() {
965         StringBuilder builder = new StringBuilder();
966         builder
967             .append("MavenDroolsController [policyContainer=")
968             .append((policyContainer != null) ? policyContainer.getName() : "NULL")
969             .append(":")
970             .append(", alive=")
971             .append(alive)
972             .append(", locked=")
973             .append(", modelClassLoaderHash=")
974             .append(modelClassLoaderHash)
975             .append("]");
976         return builder.toString();
977     }
978 }