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