2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.drools.controller.internal;
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;
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.common.utils.services.FeatureApiUtils;
45 import org.onap.policy.common.utils.services.OrderedServiceImpl;
46 import org.onap.policy.drools.controller.DroolsController;
47 import org.onap.policy.drools.controller.DroolsControllerConstants;
48 import org.onap.policy.drools.core.PolicyContainer;
49 import org.onap.policy.drools.core.PolicySession;
50 import org.onap.policy.drools.core.jmx.PdpJmx;
51 import org.onap.policy.drools.features.DroolsControllerFeatureApi;
52 import org.onap.policy.drools.features.DroolsControllerFeatureApiConstants;
53 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
54 import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants;
55 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
56 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
57 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration;
58 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder;
59 import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.PotentialCoderFilter;
60 import org.onap.policy.drools.utils.ReflectionUtil;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
65 * Maven-based Drools Controller that interacts with the
66 * policy-core PolicyContainer and PolicySession to manage
67 * Drools containers instantiated using Maven.
69 public class MavenDroolsController implements DroolsController {
71 private static final String FACT_RETRIEVE_ERROR = "Object cannot be retrieved from fact {}";
76 private static Logger logger = LoggerFactory.getLogger(MavenDroolsController.class);
79 * Policy Container, the access object to the policy-core layer.
83 protected final PolicyContainer policyContainer;
86 * alive status of this drools controller,
87 * reflects invocation of start()/stop() only.
89 protected volatile boolean alive = false;
92 * locked status of this drools controller,
93 * reflects if i/o drools related operations are permitted,
94 * more specifically: offer() and deliver().
95 * It does not affect the ability to start and stop
96 * underlying drools infrastructure
98 protected volatile boolean locked = false;
101 * list of topics, each with associated decoder classes, each
102 * with a list of associated filters.
104 protected List<TopicCoderFilterConfiguration> decoderConfigurations;
107 * list of topics, each with associated encoder classes, each
108 * with a list of associated filters.
110 protected List<TopicCoderFilterConfiguration> encoderConfigurations;
113 * recent source events processed.
115 protected final CircularFifoQueue<Object> recentSourceEvents = new CircularFifoQueue<>(10);
118 * recent sink events processed.
120 protected final CircularFifoQueue<String> recentSinkEvents = new CircularFifoQueue<>(10);
123 * original Drools Model/Rules classloader hash.
125 protected int modelClassLoaderHash;
128 * Expanded version of the constructor.
130 * @param groupId maven group id
131 * @param artifactId maven artifact id
132 * @param version maven version
133 * @param decoderConfigurations list of topic -> decoders -> filters mapping
134 * @param encoderConfigurations list of topic -> encoders -> filters mapping
136 * @throws IllegalArgumentException invalid arguments passed in
138 public MavenDroolsController(String groupId,
141 List<TopicCoderFilterConfiguration> decoderConfigurations,
142 List<TopicCoderFilterConfiguration> encoderConfigurations) {
144 logger.info("drools-controller instantiation [{}:{}:{}]", groupId, artifactId, version);
146 if (groupId == null || groupId.isEmpty()) {
147 throw new IllegalArgumentException("Missing maven group-id coordinate");
150 if (artifactId == null || artifactId.isEmpty()) {
151 throw new IllegalArgumentException("Missing maven artifact-id coordinate");
154 if (version == null || version.isEmpty()) {
155 throw new IllegalArgumentException("Missing maven version coordinate");
158 this.policyContainer = makePolicyContainer(groupId, artifactId, version);
159 this.init(decoderConfigurations, encoderConfigurations);
161 logger.debug("{}: instantiation completed ", this);
165 * init encoding/decoding configuration.
167 * @param decoderConfigurations list of topic -> decoders -> filters mapping
168 * @param encoderConfigurations list of topic -> encoders -> filters mapping
170 protected void init(List<TopicCoderFilterConfiguration> decoderConfigurations,
171 List<TopicCoderFilterConfiguration> encoderConfigurations) {
173 this.decoderConfigurations = decoderConfigurations;
174 this.encoderConfigurations = encoderConfigurations;
176 this.initCoders(decoderConfigurations, true);
177 this.initCoders(encoderConfigurations, false);
179 this.modelClassLoaderHash = this.policyContainer.getClassLoader().hashCode();
183 public void updateToVersion(String newGroupId, String newArtifactId, String newVersion,
184 List<TopicCoderFilterConfiguration> decoderConfigurations,
185 List<TopicCoderFilterConfiguration> encoderConfigurations)
186 throws LinkageError {
188 logger.info("updating version -> [{}:{}:{}]", newGroupId, newArtifactId, newVersion);
190 validateText(newGroupId, "Missing maven group-id coordinate");
191 validateText(newArtifactId, "Missing maven artifact-id coordinate");
192 validateText(newVersion, "Missing maven version coordinate");
194 validateHasBrain(newGroupId, newArtifactId, newVersion);
196 if (newGroupId.equalsIgnoreCase(this.getGroupId())
197 && newArtifactId.equalsIgnoreCase(this.getArtifactId())
198 && newVersion.equalsIgnoreCase(this.getVersion())) {
199 logger.warn("All in the right version: " + newGroupId + ":"
200 + newArtifactId + ":" + newVersion + " vs. " + this);
204 validateNewVersion(newGroupId, newArtifactId, newVersion);
207 String messages = this.policyContainer.updateToVersion(newVersion);
208 logger.warn("{} UPGRADE results: {}", this, messages);
211 * If all sucessful (can load new container), now we can remove all coders from previous sessions
218 this.init(decoderConfigurations, encoderConfigurations);
220 logger.info("UPDATE-TO-VERSION: completed {}", this);
223 private void validateText(String text, String errorMessage) {
224 if (text == null || text.isEmpty()) {
225 throw new IllegalArgumentException(errorMessage);
229 private void validateHasBrain(String newGroupId, String newArtifactId, String newVersion) {
230 if (newGroupId.equalsIgnoreCase(DroolsControllerConstants.NO_GROUP_ID)
231 || newArtifactId.equalsIgnoreCase(DroolsControllerConstants.NO_ARTIFACT_ID)
232 || newVersion.equalsIgnoreCase(DroolsControllerConstants.NO_VERSION)) {
233 throw new IllegalArgumentException("BRAINLESS maven coordinates provided: "
234 + newGroupId + ":" + newArtifactId + ":"
239 private void validateNewVersion(String newGroupId, String newArtifactId, String newVersion) {
240 if (!newGroupId.equalsIgnoreCase(this.getGroupId())
241 || !newArtifactId.equalsIgnoreCase(this.getArtifactId())) {
242 throw new IllegalArgumentException(
243 "Group ID and Artifact ID maven coordinates must be identical for the upgrade: "
244 + newGroupId + ":" + newArtifactId + ":"
245 + newVersion + " vs. " + this);
250 * initialize decoders for all the topics supported by this controller
251 * Note this is critical to be done after the Policy Container is
252 * instantiated to be able to fetch the corresponding classes.
254 * @param coderConfigurations list of topic -> decoders -> filters mapping
256 protected void initCoders(List<TopicCoderFilterConfiguration> coderConfigurations,
259 logger.info("INIT-CODERS: {}", this);
261 if (coderConfigurations == null) {
266 for (TopicCoderFilterConfiguration coderConfig: coderConfigurations) {
267 String topic = coderConfig.getTopic();
269 CustomGsonCoder customGsonCoder = getCustomCoder(coderConfig);
271 List<PotentialCoderFilter> coderFilters = coderConfig.getCoderFilters();
272 if (coderFilters == null || coderFilters.isEmpty()) {
276 for (PotentialCoderFilter coderFilter : coderFilters) {
277 String potentialCodedClass = coderFilter.getCodedClass();
278 JsonProtocolFilter protocolFilter = coderFilter.getFilter();
280 if (!isClass(potentialCodedClass)) {
281 throw makeRetrieveEx(potentialCodedClass);
283 logClassFetched(potentialCodedClass);
287 getCoderManager().addDecoder(EventProtocolParams.builder()
288 .groupId(this.getGroupId())
289 .artifactId(this.getArtifactId())
291 .eventClass(potentialCodedClass)
292 .protocolFilter(protocolFilter)
293 .customGsonCoder(customGsonCoder)
294 .modelClassLoaderHash(this.policyContainer.getClassLoader().hashCode()));
296 getCoderManager().addEncoder(
297 EventProtocolParams.builder().groupId(this.getGroupId())
298 .artifactId(this.getArtifactId()).topic(topic)
299 .eventClass(potentialCodedClass).protocolFilter(protocolFilter)
300 .customGsonCoder(customGsonCoder)
301 .modelClassLoaderHash(this.policyContainer.getClassLoader().hashCode()));
307 private CustomGsonCoder getCustomCoder(TopicCoderFilterConfiguration coderConfig) {
308 CustomGsonCoder customGsonCoder = coderConfig.getCustomGsonCoder();
309 if (customGsonCoder != null
310 && customGsonCoder.getClassContainer() != null
311 && !customGsonCoder.getClassContainer().isEmpty()) {
313 String customGsonCoderClass = customGsonCoder.getClassContainer();
314 if (!isClass(customGsonCoderClass)) {
315 throw makeRetrieveEx(customGsonCoderClass);
317 logClassFetched(customGsonCoderClass);
320 return customGsonCoder;
324 * Logs an error and makes an exception for an item that cannot be retrieved.
325 * @param itemName the item to retrieve
326 * @return a new exception
328 private IllegalArgumentException makeRetrieveEx(String itemName) {
329 logger.error("{} cannot be retrieved", itemName);
330 return new IllegalArgumentException(itemName + " cannot be retrieved");
334 * Logs the name of the class that was fetched.
335 * @param className class name fetched
337 private void logClassFetched(String className) {
338 logger.info("CLASS FETCHED {}", className);
345 protected void removeDecoders() {
346 logger.info("REMOVE-DECODERS: {}", this);
348 if (this.decoderConfigurations == null) {
353 for (TopicCoderFilterConfiguration coderConfig: decoderConfigurations) {
354 String topic = coderConfig.getTopic();
355 getCoderManager().removeDecoders(this.getGroupId(), this.getArtifactId(), topic);
362 protected void removeEncoders() {
364 logger.info("REMOVE-ENCODERS: {}", this);
366 if (this.encoderConfigurations == null) {
370 for (TopicCoderFilterConfiguration coderConfig: encoderConfigurations) {
371 String topic = coderConfig.getTopic();
372 getCoderManager().removeEncoders(this.getGroupId(), this.getArtifactId(), topic);
378 public boolean ownsCoder(Class<?> coderClass, int modelHash) {
379 if (!isClass(coderClass.getName())) {
380 logger.error("{}{} cannot be retrieved. ", this, coderClass.getName());
384 if (modelHash == this.modelClassLoaderHash) {
385 logger.info("{}{} class loader matches original drools controller rules classloader {}",
386 coderClass.getName(), this, coderClass.getClassLoader());
389 logger.warn("{}{} class loaders don't match {} vs {}", this, coderClass.getName(),
390 coderClass.getClassLoader(), this.policyContainer.getClassLoader());
396 public boolean start() {
398 logger.info("START: {}", this);
400 synchronized (this) {
407 return this.policyContainer.start();
411 public boolean stop() {
413 logger.info("STOP: {}", this);
415 synchronized (this) {
422 return this.policyContainer.stop();
426 public void shutdown() {
427 logger.info("{}: SHUTDOWN", this);
432 } catch (Exception e) {
433 logger.error("{} SHUTDOWN FAILED because of {}", this, e.getMessage(), e);
435 this.policyContainer.shutdown();
442 logger.info("{}: HALT", this);
447 } catch (Exception e) {
448 logger.error("{} HALT FAILED because of {}", this, e.getMessage(), e);
450 this.policyContainer.destroy();
455 * removes this drools controllers and encoders and decoders from operation.
457 protected void removeCoders() {
458 logger.info("{}: REMOVE-CODERS", this);
461 this.removeDecoders();
462 } catch (IllegalArgumentException e) {
463 logger.error("{} REMOVE-DECODERS FAILED because of {}", this, e.getMessage(), e);
467 this.removeEncoders();
468 } catch (IllegalArgumentException e) {
469 logger.error("{} REMOVE-ENCODERS FAILED because of {}", this, e.getMessage(), e);
474 public boolean isAlive() {
479 public boolean offer(String topic, String event) {
480 logger.debug("{}: OFFER raw event from {}", this, topic);
482 if (this.locked || !this.alive || this.policyContainer.getPolicySessions().isEmpty()) {
486 // 1. Now, check if this topic has a decoder:
488 if (!getCoderManager().isDecodingSupported(this.getGroupId(),
489 this.getArtifactId(),
492 logger.warn("{}: DECODING-UNSUPPORTED {}:{}:{}", this,
493 topic, this.getGroupId(), this.getArtifactId());
501 anEvent = getCoderManager().decode(this.getGroupId(),
502 this.getArtifactId(),
505 } catch (UnsupportedOperationException uoe) {
506 logger.debug("{}: DECODE FAILED: {} <- {} because of {}", this, topic,
507 event, uoe.getMessage(), uoe);
509 } catch (Exception e) {
510 logger.warn("{}: DECODE FAILED: {} <- {} because of {}", this, topic,
511 event, e.getMessage(), e);
515 return offer(anEvent);
520 public <T> boolean offer(T event) {
521 logger.debug("{}: OFFER event", this);
523 if (this.locked || !this.alive || this.policyContainer.getPolicySessions().isEmpty()) {
527 synchronized (this.recentSourceEvents) {
528 this.recentSourceEvents.add(event);
531 PdpJmx.getInstance().updateOccured();
535 if (FeatureApiUtils.apply(getDroolsProviders().getList(),
536 feature -> feature.beforeInsert(this, event),
537 (feature, ex) -> logger.error("{}: feature {} before-insert failure because of {}", this,
538 feature.getClass().getName(), ex.getMessage(), ex))) {
542 boolean successInject = this.policyContainer.insertAll(event);
543 if (!successInject) {
544 logger.warn(this + "Failed to inject into PolicyContainer {}", this.getSessionNames());
547 FeatureApiUtils.apply(getDroolsProviders().getList(),
548 feature -> feature.afterInsert(this, event, successInject),
549 (feature, ex) -> logger.error("{}: feature {} after-insert failure because of {}", this,
550 feature.getClass().getName(), ex.getMessage(), ex));
557 public boolean deliver(TopicSink sink, Object event) {
559 logger.info("{}DELIVER: {} FROM {} TO {}", this, event, this, sink);
561 for (DroolsControllerFeatureApi feature : getDroolsProviders().getList()) {
563 if (feature.beforeDeliver(this, sink, event)) {
567 catch (Exception e) {
568 logger.error("{}: feature {} before-deliver failure because of {}", this, feature.getClass().getName(),
574 throw new IllegalArgumentException(this + " invalid sink");
578 throw new IllegalArgumentException(this + " invalid event");
582 throw new IllegalStateException(this + " is locked");
586 throw new IllegalStateException(this + " is stopped");
590 getCoderManager().encode(sink.getTopic(), event, this);
592 synchronized (this.recentSinkEvents) {
593 this.recentSinkEvents.add(json);
596 boolean success = sink.send(json);
598 for (DroolsControllerFeatureApi feature : getDroolsProviders().getList()) {
600 if (feature.afterDeliver(this, sink, event, json, success)) {
604 catch (Exception e) {
605 logger.error("{}: feature {} after-deliver failure because of {}", this, feature.getClass().getName(),
615 public String getVersion() {
616 return this.policyContainer.getVersion();
620 public String getArtifactId() {
621 return this.policyContainer.getArtifactId();
625 public String getGroupId() {
626 return this.policyContainer.getGroupId();
630 * Get model class loader hash.
632 * @return the modelClassLoaderHash
634 public int getModelClassLoaderHash() {
635 return modelClassLoaderHash;
639 public synchronized boolean lock() {
640 logger.info("LOCK: {}", this);
647 public synchronized boolean unlock() {
648 logger.info("UNLOCK: {}", this);
655 public boolean isLocked() {
662 public PolicyContainer getContainer() {
663 return this.policyContainer;
666 @JsonProperty("sessions")
667 @GsonJsonProperty("sessions")
669 public List<String> getSessionNames() {
670 return getSessionNames(true);
676 * @param abbreviated true for the short form, otherwise the long form
677 * @return session names
679 protected List<String> getSessionNames(boolean abbreviated) {
680 List<String> sessionNames = new ArrayList<>();
682 for (PolicySession session: this.policyContainer.getPolicySessions()) {
684 sessionNames.add(session.getName());
686 sessionNames.add(session.getFullName());
689 } catch (Exception e) {
690 logger.warn("Can't retrieve CORE sessions: " + e.getMessage(), e);
691 sessionNames.add(e.getMessage());
696 @JsonProperty("sessionCoordinates")
697 @GsonJsonProperty("sessionCoordinates")
699 public List<String> getCanonicalSessionNames() {
700 return getSessionNames(false);
704 public List<String> getBaseDomainNames() {
705 return new ArrayList<>(this.policyContainer.getKieContainer().getKieBaseNames());
709 * provides the underlying core layer container sessions.
711 * @return the attached Policy Container
713 protected List<PolicySession> getSessions() {
714 List<PolicySession> sessions = new ArrayList<>();
715 sessions.addAll(this.policyContainer.getPolicySessions());
720 * provides the underlying core layer container session with name sessionName.
722 * @param sessionName session name
723 * @return the attached Policy Container
724 * @throws IllegalArgumentException when an invalid session name is provided
725 * @throws IllegalStateException when the drools controller is in an invalid state
727 protected PolicySession getSession(String sessionName) {
728 if (sessionName == null || sessionName.isEmpty()) {
729 throw new IllegalArgumentException("A Session Name must be provided");
732 List<PolicySession> sessions = this.getSessions();
733 for (PolicySession session : sessions) {
734 if (sessionName.equals(session.getName()) || sessionName.equals(session.getFullName())) {
739 throw invalidSessNameEx(sessionName);
742 private IllegalArgumentException invalidSessNameEx(String sessionName) {
743 return new IllegalArgumentException("Invalid Session Name: " + sessionName);
747 public Map<String,Integer> factClassNames(String sessionName) {
748 validateSessionName(sessionName);
750 Map<String,Integer> classNames = new HashMap<>();
752 PolicySession session = getSession(sessionName);
753 KieSession kieSession = session.getKieSession();
755 Collection<FactHandle> facts = kieSession.getFactHandles();
756 for (FactHandle fact : facts) {
758 String className = kieSession.getObject(fact).getClass().getName();
759 if (classNames.containsKey(className)) {
760 classNames.put(className, classNames.get(className) + 1);
762 classNames.put(className, 1);
764 } catch (Exception e) {
765 logger.warn(FACT_RETRIEVE_ERROR, fact, e);
772 private void validateSessionName(String sessionName) {
773 if (sessionName == null || sessionName.isEmpty()) {
774 throw invalidSessNameEx(sessionName);
779 public long factCount(String sessionName) {
780 validateSessionName(sessionName);
782 PolicySession session = getSession(sessionName);
783 return session.getKieSession().getFactCount();
787 public List<Object> facts(String sessionName, String className, boolean delete) {
788 validateSessionName(sessionName);
790 if (className == null || className.isEmpty()) {
791 throw new IllegalArgumentException("Invalid Class Name: " + className);
795 ReflectionUtil.fetchClass(this.policyContainer.getClassLoader(), className);
796 if (factClass == null) {
797 throw new IllegalArgumentException("Class cannot be fetched in model's classloader: " + className);
800 PolicySession session = getSession(sessionName);
801 KieSession kieSession = session.getKieSession();
803 List<Object> factObjects = new ArrayList<>();
805 Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(factClass));
806 for (FactHandle factHandle : factHandles) {
808 factObjects.add(kieSession.getObject(factHandle));
810 kieSession.delete(factHandle);
812 } catch (Exception e) {
813 logger.warn(FACT_RETRIEVE_ERROR, factHandle, e);
821 public <T> List<T> facts(@NonNull String sessionName, @NonNull Class<T> clazz) {
822 return facts(sessionName, clazz.getName(), false)
824 .filter(clazz::isInstance)
826 .collect(Collectors.toList());
830 public List<Object> factQuery(String sessionName, String queryName, String queriedEntity,
831 boolean delete, Object... queryParams) {
832 validateSessionName(sessionName);
834 if (queryName == null || queryName.isEmpty()) {
835 throw new IllegalArgumentException("Invalid Query Name: " + queryName);
838 if (queriedEntity == null || queriedEntity.isEmpty()) {
839 throw new IllegalArgumentException("Invalid Queried Entity: " + queriedEntity);
842 PolicySession session = getSession(sessionName);
843 KieSession kieSession = session.getKieSession();
845 validateQueryName(kieSession, queryName);
847 List<Object> factObjects = new ArrayList<>();
849 QueryResults queryResults = kieSession.getQueryResults(queryName, queryParams);
850 for (QueryResultsRow row : queryResults) {
852 factObjects.add(row.get(queriedEntity));
854 kieSession.delete(row.getFactHandle(queriedEntity));
856 } catch (Exception e) {
857 logger.warn("Object cannot be retrieved from row: {}", row, e);
864 private void validateQueryName(KieSession kieSession, String queryName) {
865 for (KiePackage kiePackage : kieSession.getKieBase().getKiePackages()) {
866 for (Query q : kiePackage.getQueries()) {
867 if (q.getName() != null && q.getName().equals(queryName)) {
873 throw new IllegalArgumentException("Invalid Query Name: " + queryName);
877 public <T> boolean delete(@NonNull String sessionName, @NonNull T fact) {
878 String factClassName = fact.getClass().getName();
880 PolicySession session = getSession(sessionName);
881 KieSession kieSession = session.getKieSession();
883 Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(fact.getClass()));
884 for (FactHandle factHandle : factHandles) {
886 if (Objects.equals(fact, kieSession.getObject(factHandle))) {
887 logger.info("Deleting {} from {}", factClassName, sessionName);
888 kieSession.delete(factHandle);
891 } catch (Exception e) {
892 logger.warn(FACT_RETRIEVE_ERROR, factHandle, e);
899 public <T> boolean delete(@NonNull T fact) {
900 return this.getSessionNames().stream().map(ss -> delete(ss, fact)).reduce(false, Boolean::logicalOr);
904 public <T> boolean delete(@NonNull String sessionName, @NonNull Class<T> fact) {
905 PolicySession session = getSession(sessionName);
906 KieSession kieSession = session.getKieSession();
908 boolean success = true;
909 Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(fact));
910 for (FactHandle factHandle : factHandles) {
912 kieSession.delete(factHandle);
913 } catch (Exception e) {
914 logger.warn(FACT_RETRIEVE_ERROR, factHandle, e);
922 public <T> boolean delete(@NonNull Class<T> fact) {
923 return this.getSessionNames().stream().map(ss -> delete(ss, fact)).reduce(false, Boolean::logicalOr);
928 public Class<?> fetchModelClass(String className) {
929 return ReflectionUtil.fetchClass(this.policyContainer.getClassLoader(), className);
933 * Get recent source events.
935 * @return the recentSourceEvents
938 public Object[] getRecentSourceEvents() {
939 synchronized (this.recentSourceEvents) {
940 Object[] events = new Object[recentSourceEvents.size()];
941 return recentSourceEvents.toArray(events);
946 * Get recent sink events.
948 * @return the recentSinkEvents
951 public String[] getRecentSinkEvents() {
952 synchronized (this.recentSinkEvents) {
953 String[] events = new String[recentSinkEvents.size()];
954 return recentSinkEvents.toArray(events);
959 public boolean isBrained() {
965 public String toString() {
966 StringBuilder builder = new StringBuilder();
968 .append("MavenDroolsController [policyContainer=")
969 .append(policyContainer.getName())
974 .append(", modelClassLoaderHash=")
975 .append(modelClassLoaderHash)
977 return builder.toString();
980 // these may be overridden by junit tests
982 protected EventProtocolCoder getCoderManager() {
983 return EventProtocolCoderConstants.getManager();
986 protected OrderedServiceImpl<DroolsControllerFeatureApi> getDroolsProviders() {
987 return DroolsControllerFeatureApiConstants.getProviders();
990 protected PolicyContainer makePolicyContainer(String groupId, String artifactId, String version) {
991 return new PolicyContainer(groupId, artifactId, version);
994 protected boolean isClass(String className) {
995 return ReflectionUtil.isClass(this.policyContainer.getClassLoader(), className);