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