diff options
98 files changed, 1843 insertions, 1316 deletions
diff --git a/api-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeatureApi.java b/api-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeatureApi.java index 8637fa5c..5be1c526 100644 --- a/api-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeatureApi.java +++ b/api-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeatureApi.java @@ -21,7 +21,6 @@ package org.onap.policy.drools.activestandby; import org.onap.policy.common.utils.services.OrderedService; -import org.onap.policy.common.utils.services.OrderedServiceImpl; /** * This interface provides a way to invoke optional features at various points in the code. At @@ -29,12 +28,6 @@ import org.onap.policy.common.utils.services.OrderedServiceImpl; * optional methods. */ public interface ActiveStandbyFeatureApi extends OrderedService { - /** - * 'FeatureAPI.impl.getList()' returns an ordered list of objects implementing the 'FeatureAPI' - * interface. - */ - public static OrderedServiceImpl<ActiveStandbyFeatureApi> impl = - new OrderedServiceImpl<>(ActiveStandbyFeatureApi.class); /** * Returns the resourceName (PDP ID) for the Drools-PDP that is diff --git a/api-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeatureApiConstants.java b/api-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeatureApiConstants.java new file mode 100644 index 00000000..48f41a68 --- /dev/null +++ b/api-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeatureApiConstants.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * api-active-standby-management + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import lombok.Getter; +import org.onap.policy.common.utils.services.OrderedServiceImpl; + +public class ActiveStandbyFeatureApiConstants { + /** + * 'FeatureAPI.impl.getList()' returns an ordered list of objects implementing the 'FeatureAPI' + * interface. + */ + @Getter + private static final OrderedServiceImpl<ActiveStandbyFeatureApi> impl = + new OrderedServiceImpl<>(ActiveStandbyFeatureApi.class); + + private ActiveStandbyFeatureApiConstants() { + // do nothing + } +} diff --git a/api-state-management/pom.xml b/api-state-management/pom.xml index c02542e2..1685cbcb 100644 --- a/api-state-management/pom.xml +++ b/api-state-management/pom.xml @@ -42,15 +42,20 @@ <dependencies> <dependency> - <groupId>org.onap.policy.drools-pdp</groupId> - <artifactId>policy-core</artifactId> - <version>${project.version}</version> - <scope>provided</scope> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>policy-core</artifactId> + <version>${project.version}</version> + <scope>provided</scope> </dependency> <dependency> - <groupId>org.onap.policy.common</groupId> - <artifactId>integrity-monitor</artifactId> - <version>${policy.common.version}</version> + <groupId>org.onap.policy.common</groupId> + <artifactId>integrity-monitor</artifactId> + <version>${policy.common.version}</version> + </dependency> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <scope>provided</scope> </dependency> </dependencies> diff --git a/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureApi.java b/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureApi.java index dcb784e3..d2c7b390 100644 --- a/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureApi.java +++ b/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureApi.java @@ -21,14 +21,10 @@ package org.onap.policy.drools.statemanagement; import java.util.Observer; - import javax.validation.constraints.NotNull; - import org.onap.policy.common.capabilities.Lockable; import org.onap.policy.common.im.AllSeemsWellException; -import org.onap.policy.common.im.StateManagement; import org.onap.policy.common.utils.services.OrderedService; -import org.onap.policy.common.utils.services.OrderedServiceImpl; /** * This interface provides a way to invoke optional features at various points in the code. At @@ -38,42 +34,6 @@ import org.onap.policy.common.utils.services.OrderedServiceImpl; */ public interface StateManagementFeatureApi extends OrderedService, Lockable { - public static final String LOCKED = StateManagement.LOCKED; - public static final String UNLOCKED = StateManagement.UNLOCKED; - public static final String ENABLED = StateManagement.ENABLED; - public static final String DISABLED = StateManagement.DISABLED; - public static final String ENABLE_NOT_FAILED = StateManagement.ENABLE_NOT_FAILED_ACTION; - public static final String DISABLE_FAILED = StateManagement.DISABLE_FAILED_ACTION; - public static final String FAILED = StateManagement.FAILED; - public static final String DEPENDENCY = StateManagement.DEPENDENCY; - public static final String DEPENDENCY_FAILED = StateManagement.DEPENDENCY_FAILED; - public static final String DISABLE_DEPENDENCY = StateManagement.DISABLE_DEPENDENCY_ACTION; - public static final String ENABLE_NO_DEPENDENCY = StateManagement.ENABLE_NO_DEPENDENCY_ACTION; - public static final String NULL_VALUE = StateManagement.NULL_VALUE; - public static final String DO_LOCK = StateManagement.LOCK_ACTION; - public static final String DO_UNLOCK = StateManagement.UNLOCK_ACTION; - public static final String DO_PROMOTE = StateManagement.PROMOTE_ACTION; - public static final String DO_DEMOTE = StateManagement.DEMOTE_ACTION; - public static final String HOT_STANDBY = StateManagement.HOT_STANDBY; - public static final String COLD_STANDBY = StateManagement.COLD_STANDBY; - public static final String PROVIDING_SERVICE = StateManagement.PROVIDING_SERVICE; - - public static final String ADMIN_STATE = StateManagement.ADMIN_STATE; - public static final String OPERATION_STATE = StateManagement.OPERATION_STATE; - public static final String AVAILABLE_STATUS = StateManagement.AVAILABLE_STATUS; - public static final String STANDBY_STATUS = StateManagement.STANDBY_STATUS; - - public static final Boolean ALLSEEMSWELL_STATE = Boolean.TRUE; - public static final Boolean ALLNOTWELL_STATE = Boolean.FALSE; - - public static final int SEQ_NUM = 0; - /** - * 'FeatureAPI.impl.getList()' returns an ordered list of objects implementing the 'FeatureAPI' - * interface. - */ - public static OrderedServiceImpl<StateManagementFeatureApi> impl = - new OrderedServiceImpl<>(StateManagementFeatureApi.class); - /** * ALL SEEMS/NOT WELL This interface is used to support the concept of All Seems/Not Well. It * provides a way for client code to indicate to the DroolsPDPIntegrityMonitor that an event has diff --git a/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureApiConstants.java b/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureApiConstants.java new file mode 100644 index 00000000..be51a502 --- /dev/null +++ b/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureApiConstants.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * policy-core + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.statemanagement; + +import lombok.Getter; +import org.onap.policy.common.im.StateManagement; +import org.onap.policy.common.utils.services.OrderedServiceImpl; + +public class StateManagementFeatureApiConstants { + + public static final String LOCKED = StateManagement.LOCKED; + public static final String UNLOCKED = StateManagement.UNLOCKED; + public static final String ENABLED = StateManagement.ENABLED; + public static final String DISABLED = StateManagement.DISABLED; + public static final String ENABLE_NOT_FAILED = StateManagement.ENABLE_NOT_FAILED_ACTION; + public static final String DISABLE_FAILED = StateManagement.DISABLE_FAILED_ACTION; + public static final String FAILED = StateManagement.FAILED; + public static final String DEPENDENCY = StateManagement.DEPENDENCY; + public static final String DEPENDENCY_FAILED = StateManagement.DEPENDENCY_FAILED; + public static final String DISABLE_DEPENDENCY = StateManagement.DISABLE_DEPENDENCY_ACTION; + public static final String ENABLE_NO_DEPENDENCY = StateManagement.ENABLE_NO_DEPENDENCY_ACTION; + public static final String NULL_VALUE = StateManagement.NULL_VALUE; + public static final String DO_LOCK = StateManagement.LOCK_ACTION; + public static final String DO_UNLOCK = StateManagement.UNLOCK_ACTION; + public static final String DO_PROMOTE = StateManagement.PROMOTE_ACTION; + public static final String DO_DEMOTE = StateManagement.DEMOTE_ACTION; + public static final String HOT_STANDBY = StateManagement.HOT_STANDBY; + public static final String COLD_STANDBY = StateManagement.COLD_STANDBY; + public static final String PROVIDING_SERVICE = StateManagement.PROVIDING_SERVICE; + + public static final String ADMIN_STATE = StateManagement.ADMIN_STATE; + public static final String OPERATION_STATE = StateManagement.OPERATION_STATE; + public static final String AVAILABLE_STATUS = StateManagement.AVAILABLE_STATUS; + public static final String STANDBY_STATUS = StateManagement.STANDBY_STATUS; + + public static final Boolean ALLSEEMSWELL_STATE = Boolean.TRUE; + public static final Boolean ALLNOTWELL_STATE = Boolean.FALSE; + + public static final int SEQ_NUM = 0; + + /** + * 'FeatureAPI.impl.getList()' returns an ordered list of objects implementing the 'FeatureAPI' + * interface. + */ + @Getter + private static final OrderedServiceImpl<StateManagementFeatureApi> impl = + new OrderedServiceImpl<>(StateManagementFeatureApi.class); + + private StateManagementFeatureApiConstants() { + // do nothing + } +} diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java index 2be44458..d7c153db 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java @@ -32,7 +32,9 @@ import javax.persistence.Persistence; import org.onap.policy.drools.core.PolicySessionFeatureApi; import org.onap.policy.drools.features.PolicyEngineFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; +import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.system.PolicyEngineConstants; import org.onap.policy.drools.utils.PropertyUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -82,7 +84,7 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi, // This must come first since it initializes myPdp initializePersistence(configDir); - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { if (feature.getResourceName().equals(myPdp.getPdpId())) { logger.debug("ActiveStandbyFeature.globalInit: Found StateManagementFeature" + " with resourceName: {}", myPdp.getPdpId()); @@ -120,7 +122,7 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi, @Override public boolean afterStart(PolicyEngine engine) { // ASSERTION: engine == PolicyEngine.manager - PolicyEngine.manager.lock(); + PolicyEngineConstants.getManager().lock(); return false; } @@ -169,7 +171,7 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi, } else { siteName = siteName.trim(); } - myPdp.setSiteName(siteName); + myPdp.setSite(siteName); if (electionHandler == null) { electionHandler = new DroolsPdpsElectionHandler(conn,myPdp); } diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdp.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdp.java index 46096bdd..8fada968 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdp.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdp.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * feature-active-standby-management * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,26 +25,26 @@ import java.util.Date; public interface DroolsPdp { public String getPdpId(); - + public boolean isDesignated(); - + public int getPriority(); - + public Date getUpdatedDate(); - + public void setDesignated(boolean isDesignated); - + public void setUpdatedDate(Date updatedDate); - + public int comparePriority(DroolsPdp other); - + public int comparePriority(DroolsPdp other,String previousSite); - - public String getSiteName(); - - public void setSiteName(String siteName); - + + public String getSite(); + + public void setSite(String site); + public Date getDesignatedDate(); - + public void setDesignatedDate(Date designatedDate); } diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java index 0055b9cb..38ab6e4b 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java @@ -30,7 +30,8 @@ import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Temporal; import javax.persistence.TemporalType; - +import lombok.Getter; +import lombok.Setter; import org.onap.policy.drools.activestandby.DroolsPdpObject; @Entity @@ -40,6 +41,8 @@ import org.onap.policy.drools.activestandby.DroolsPdpObject; @NamedQuery(name = "DroolsPdpEntity.findAll", query = "SELECT e FROM DroolsPdpEntity e "), @NamedQuery(name = "DroolsPdpEntity.deleteAll", query = "DELETE FROM DroolsPdpEntity WHERE 1=1") }) +@Getter +@Setter public class DroolsPdpEntity extends DroolsPdpObject implements Serializable { private static final long serialVersionUID = 1L; @@ -77,62 +80,12 @@ public class DroolsPdpEntity extends DroolsPdpObject implements Serializable { } @Override - public String getPdpId() { - return this.pdpId; - } - - public void setPdpId(String pdpId) { - this.pdpId = pdpId; - } - - @Override - public boolean isDesignated() { - return this.designated; - } - - @Override - public int getPriority() { - return this.priority; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - @Override - public Date getUpdatedDate() { - return this.updatedDate; - } - - @Override - public void setDesignated(boolean isDesignated) { - this.designated = isDesignated; - } - - @Override - public void setUpdatedDate(Date updatedDate) { - this.updatedDate = updatedDate; - } - - - @Override - public String getSiteName() { - return site; - } - - @Override - public void setSiteName(String siteName) { - site = siteName; - - } - - @Override - public Date getDesignatedDate() { - return designatedDate; + public int hashCode() { + return super.hashCode(); } @Override - public void setDesignatedDate(Date designatedDate) { - this.designatedDate = designatedDate; + public boolean equals(Object obj) { + return super.equals(obj); } } diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpImpl.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpImpl.java index 0c50f82d..41d58602 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpImpl.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpImpl.java @@ -21,7 +21,11 @@ package org.onap.policy.drools.activestandby; import java.util.Date; +import lombok.Getter; +import lombok.Setter; +@Getter +@Setter public class DroolsPdpImpl extends DroolsPdpObject { private boolean designated; @@ -48,60 +52,15 @@ public class DroolsPdpImpl extends DroolsPdpObject { //to the local timezone. So, a value of Date(0) is actually Dec 31 18:00:00 CST 1969 //which is an invalid value for the MySql TimeStamp this.designatedDate = new Date(864000000); - - } - - @Override - public boolean isDesignated() { - - return designated; - } - - @Override - public int getPriority() { - return priority; } @Override - public void setUpdatedDate(Date date) { - this.updatedDate = date; + public int hashCode() { + return super.hashCode(); } @Override - public Date getUpdatedDate() { - return updatedDate; - } - - @Override - public String getPdpId() { - return pdpId; - } - - @Override - public void setDesignated(boolean isDesignated) { - this.designated = isDesignated; - - } - - @Override - public String getSiteName() { - return site; - } - - @Override - public void setSiteName(String siteName) { - this.site = siteName; - - } - - @Override - public Date getDesignatedDate() { - return designatedDate; - } - - @Override - public void setDesignatedDate(Date designatedDate) { - this.designatedDate = designatedDate; - + public boolean equals(Object obj) { + return super.equals(obj); } } diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpObject.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpObject.java index 75157bbe..f753c0aa 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpObject.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpObject.java @@ -71,13 +71,13 @@ public abstract class DroolsPdpObject implements DroolsPdp { } private int commonCompare(DroolsPdp other) { - if (nullSafeCompare(this.getSiteName(),other.getSiteName()) == 0) { + if (nullSafeCompare(this.getSite(),other.getSite()) == 0) { if (this.getPriority() != other.getPriority()) { return this.getPriority() - other.getPriority(); } return this.getPdpId().compareTo(other.getPdpId()); } else { - return nullSafeCompare(this.getSiteName(),other.getSiteName()); + return nullSafeCompare(this.getSite(),other.getSite()); } } } diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java index cd8d369f..33c8a8d8 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java @@ -29,10 +29,13 @@ import java.util.TimerTask; import org.onap.policy.common.im.StateManagement; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; +import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DroolsPdpsElectionHandler implements ThreadRunningChecker { + private static final String RUN_PRIMARY_MSG = "DesignatedWaiter.run mostRecentPrimary = {}"; + // get an instance of logger private static final Logger logger = LoggerFactory.getLogger(DroolsPdpsElectionHandler.class); private DroolsPdpsConnector pdpsConnector; @@ -135,7 +138,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { //Get the StateManagementFeature instance - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { if (feature.getResourceName().equals(myPdp.getPdpId())) { logger.debug("DroolsPdpsElectionHandler: Found StateManagementFeature" + " with resourceName: {}", myPdp.getPdpId()); @@ -625,7 +628,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } } DroolsPdp mostRecentPrimary = new DroolsPdpImpl(null, true, 1, new Date(0)); - mostRecentPrimary.setSiteName(null); + mostRecentPrimary.setSite(null); logger.debug("DesignatedWaiter.run listOfDesignated.size() = {}", listOfDesignated.size()); if (listOfDesignated.size() <= 1) { logger.debug("DesignatedWainter.run: listOfDesignated.size <=1"); @@ -636,8 +639,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { pdp.getPdpId(), pdp.getDesignatedDate()); if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0) { mostRecentPrimary = pdp; - logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", - mostRecentPrimary.getPdpId()); + logger.debug(RUN_PRIMARY_MSG, mostRecentPrimary.getPdpId()); } } } else if (listOfDesignated.size() == pdps.size()) { @@ -652,12 +654,12 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { if (containsDesignated) { //Choose the site of the first designated date if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) < 0) { mostRecentPrimary = pdp; - logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); + logger.debug(RUN_PRIMARY_MSG, mostRecentPrimary.getPdpId()); } } else { //Choose the site with the latest designated date if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0) { mostRecentPrimary = pdp; - logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); + logger.debug(RUN_PRIMARY_MSG, mostRecentPrimary.getPdpId()); } } } @@ -679,7 +681,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0) { mostRecentPrimary = pdp; - logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); + logger.debug(RUN_PRIMARY_MSG, mostRecentPrimary.getPdpId()); } } } else { @@ -688,7 +690,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { for (DroolsPdp pdp : pdps) { if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0) { mostRecentPrimary = pdp; - logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); + logger.debug(RUN_PRIMARY_MSG, mostRecentPrimary.getPdpId()); } } } @@ -714,7 +716,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { DroolsPdp lowestPriorityDifferentSite = null; for (DroolsPdp pdp : listOfDesignated) { // We need to determine if another PDP is the lowest priority - if (nullSafeEquals(pdp.getSiteName(),mostRecentPrimary.getSiteName())) { + if (nullSafeEquals(pdp.getSite(),mostRecentPrimary.getSite())) { if (lowestPrioritySameSite == null) { if (lowestPriorityDifferentSite != null) { rejectedPdp = lowestPriorityDifferentSite; @@ -858,7 +860,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { allSeemsWell = false; logger.debug("checkWaitTimer: calling allSeemsWell with ALLNOTWELL param"); stateManagementFeature.allSeemsWell(this.getClass().getName(), - StateManagementFeatureApi.ALLNOTWELL_STATE, + StateManagementFeatureApiConstants.ALLNOTWELL_STATE, "DesignationWaiter/ElectionHandler has STALLED"); } logger.error("checkWaitTimer: nowMs - waitTimerMs = {}" @@ -867,7 +869,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } else if (allSeemsWell == null || !allSeemsWell) { allSeemsWell = true; stateManagementFeature.allSeemsWell(this.getClass().getName(), - StateManagementFeatureApi.ALLSEEMSWELL_STATE, + StateManagementFeatureApiConstants.ALLSEEMSWELL_STATE, "DesignationWaiter/ElectionHandler has RESUMED"); logger.info("DesignationWaiter/ElectionHandler has RESUMED"); } diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java index 30952af1..078c891f 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java @@ -36,6 +36,9 @@ import org.slf4j.LoggerFactory; public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { + private static final String SELECT_PDP_BY_ID = "SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"; + private static final String PDP_ID_PARAM = "pdpId"; + // get an instance of logger private static final Logger logger = LoggerFactory.getLogger(JpaDroolsPdpsConnector.class); private EntityManagerFactory emf; @@ -102,8 +105,8 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { EntityManager em = emf.createEntityManager(); try { em.getTransaction().begin(); - Query droolsPdpsListQuery = em.createQuery("SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"); - droolsPdpsListQuery.setParameter("pdpId", pdp.getPdpId()); + Query droolsPdpsListQuery = em.createQuery(SELECT_PDP_BY_ID); + droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdp.getPdpId()); List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE) .setFlushMode(FlushModeType.COMMIT).getResultList(); DroolsPdpEntity droolsPdpEntity; @@ -138,8 +141,8 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { if (!droolsPdpEntity.getUpdatedDate().equals(pdp.getUpdatedDate())) { droolsPdpEntity.setUpdatedDate(pdp.getUpdatedDate()); } - if (!nullSafeEquals(droolsPdpEntity.getSiteName(),pdp.getSiteName())) { - droolsPdpEntity.setSiteName(pdp.getSiteName()); + if (!nullSafeEquals(droolsPdpEntity.getSite(),pdp.getSite())) { + droolsPdpEntity.setSite(pdp.getSite()); } if (droolsPdpEntity.isDesignated() != pdp.isDesignated()) { @@ -178,8 +181,8 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { try { if (!isCurrent && pdp.isDesignated()) { em.getTransaction().begin(); - Query droolsPdpsListQuery = em.createQuery("SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"); - droolsPdpsListQuery.setParameter("pdpId", pdp.getPdpId()); + Query droolsPdpsListQuery = em.createQuery(SELECT_PDP_BY_ID); + droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdp.getPdpId()); List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE) .setFlushMode(FlushModeType.COMMIT).getResultList(); if (droolsPdpsList.size() == 1 && droolsPdpsList.get(0) instanceof DroolsPdpEntity) { @@ -217,8 +220,8 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { em = emf.createEntityManager(); em.getTransaction().begin(); Query droolsPdpsListQuery = em - .createQuery("SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"); - droolsPdpsListQuery.setParameter("pdpId", pdp.getPdpId()); + .createQuery(SELECT_PDP_BY_ID); + droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdp.getPdpId()); List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode( LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); if (droolsPdpsList.size() == 1 @@ -271,8 +274,8 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { * false. */ Query droolsPdpsListQuery = em - .createQuery("SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"); - droolsPdpsListQuery.setParameter("pdpId", pdpId); + .createQuery(SELECT_PDP_BY_ID); + droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdpId); List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode( LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); DroolsPdpEntity droolsPdpEntity; @@ -398,8 +401,8 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { em = emf.createEntityManager(); em.getTransaction().begin(); Query droolsPdpsListQuery = em - .createQuery("SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"); - droolsPdpsListQuery.setParameter("pdpId", pdpId); + .createQuery(SELECT_PDP_BY_ID); + droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdpId); List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode( LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); if (droolsPdpsList.size() == 1 @@ -454,7 +457,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { droolsPdpEntity.setDesignated(pdp.isDesignated()); droolsPdpEntity.setPriority(pdp.getPriority()); droolsPdpEntity.setUpdatedDate(pdp.getUpdatedDate()); - droolsPdpEntity.setSiteName(pdp.getSiteName()); + droolsPdpEntity.setSite(pdp.getSite()); /* * End transaction. diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java index bdd9a958..3f4ae557 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java @@ -46,6 +46,7 @@ import java.util.TimerTask; import org.onap.policy.common.im.StateChangeNotifier; import org.onap.policy.common.im.StateManagement; import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.system.PolicyEngineConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -287,7 +288,7 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { isWaitingForActivation = false; isNowActivating = false; logger.warn("DelayActivateClass.run: caught an unexpected exception " - + "calling PolicyEngine.manager.activate: ", e); + + "calling PolicyEngineConstants.getManager().activate: ", e); } } } @@ -299,7 +300,7 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { // these may be overridden by junit tests protected PolicyEngine getPolicyEngineManager() { - return PolicyEngine.manager; + return PolicyEngineConstants.getManager(); } protected Timer makeTimer() { diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/DroolsPdpObjectTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/DroolsPdpObjectTest.java index 842d6c7f..52000fd5 100644 --- a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/DroolsPdpObjectTest.java +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/DroolsPdpObjectTest.java @@ -87,7 +87,7 @@ public class DroolsPdpObjectTest { @Test public void testNullSafeCompare() { // self, when null - pdp.setSiteName(null); + pdp.setSite(null); assertEquals(0, pdp.comparePriority(pdp)); // both null @@ -138,7 +138,7 @@ public class DroolsPdpObjectTest { }; pdp2.setPdpId(PDP_ID); - pdp2.setSiteName(SITE2); + pdp2.setSite(SITE2); pdp2.setPriority(PRIORITY); // should use overridden comparison method @@ -152,7 +152,7 @@ public class DroolsPdpObjectTest { private MyPdp makePdp(String id, String site, int priority) { MyPdp pdp2 = new MyPdp(); - pdp2.setSiteName(site); + pdp2.setSite(site); pdp2.setPdpId(id); pdp2.setPriority(priority); @@ -166,7 +166,7 @@ public class DroolsPdpObjectTest { private boolean designated; private int priority; private Date updatedDate; - private String siteName; + private String site; private Date designatedDate; } } diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java index b5b89941..5e9b360f 100644 --- a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java @@ -39,6 +39,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.im.StateManagement; import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApi; +import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApiConstants; import org.onap.policy.drools.activestandby.ActiveStandbyProperties; import org.onap.policy.drools.activestandby.DroolsPdpEntity; import org.onap.policy.drools.activestandby.DroolsPdpImpl; @@ -47,6 +48,7 @@ import org.onap.policy.drools.activestandby.DroolsPdpsElectionHandler; import org.onap.policy.drools.activestandby.JpaDroolsPdpsConnector; import org.onap.policy.drools.core.PolicySessionFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; +import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -235,7 +237,7 @@ public class AllSeemsWellTest { // discovered by the ActiveStandbyFeature when the election handler initializes. StateManagementFeatureApi stateManagementFeatureApi = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); stateManagementFeatureApi = feature; logger.debug("testAllSeemsWell stateManagementFeature.getResourceName(): {}", @@ -255,7 +257,7 @@ public class AllSeemsWellTest { // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApi.impl.getList()) { + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); activeStandbyFeature = feature; logger.debug("testAllSeemsWell activeStandbyFeature.getResourceName(): {}", diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java index b277850c..8bc8489a 100644 --- a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java @@ -44,6 +44,7 @@ import org.onap.policy.common.im.IntegrityMonitor; import org.onap.policy.common.im.StandbyStatusException; import org.onap.policy.common.im.StateManagement; import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApi; +import org.onap.policy.drools.activestandby.ActiveStandbyFeatureApiConstants; import org.onap.policy.drools.activestandby.ActiveStandbyProperties; import org.onap.policy.drools.activestandby.DroolsPdp; import org.onap.policy.drools.activestandby.DroolsPdpEntity; @@ -54,6 +55,7 @@ import org.onap.policy.drools.activestandby.JpaDroolsPdpsConnector; import org.onap.policy.drools.activestandby.PmStandbyStateChangeNotifier; import org.onap.policy.drools.core.PolicySessionFeatureApi; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; +import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -352,7 +354,7 @@ public class StandbyStateManagementTest { // discovered by the ActiveStandbyFeature when the election handler initializes. StateManagementFeatureApi stateManagementFeature = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); stateManagementFeature = feature; logger.debug("testColdStandby stateManagementFeature.getResourceName(): {}", @@ -471,7 +473,7 @@ public class StandbyStateManagementTest { // discovered by the ActiveStandbyFeature when the election handler initializes. StateManagementFeatureApi stateManagementFeature = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); stateManagementFeature = feature; logger.debug("testComputeMostRecentPrimary stateManagementFeature.getResourceName(): {}", @@ -620,21 +622,21 @@ public class StandbyStateManagementTest { long designatedDateMs = new Date().getTime(); DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date()); pdp1.setDesignatedDate(new Date(designatedDateMs - 2)); - pdp1.setSiteName("site1"); + pdp1.setSite("site1"); DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date()); pdp2.setDesignatedDate(new Date(designatedDateMs - 3)); - pdp2.setSiteName("site1"); + pdp2.setSite("site1"); //oldest DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date()); pdp3.setDesignatedDate(new Date(designatedDateMs - 4)); - pdp3.setSiteName("site2"); + pdp3.setSite("site2"); DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date()); //most recent pdp4.setDesignatedDate(new Date(designatedDateMs)); - pdp4.setSiteName("site2"); + pdp4.setSite("site2"); ArrayList<DroolsPdp> listOfAllPdps = new ArrayList<DroolsPdp>(); listOfAllPdps.add(pdp1); @@ -653,7 +655,7 @@ public class StandbyStateManagementTest { // discovered by the ActiveStandbyFeature when the election handler initializes. StateManagementFeatureApi stateManagementFeature = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); stateManagementFeature = feature; logger.debug("testComputeDesignatedPdp stateManagementFeature.getResourceName(): {}", @@ -793,7 +795,7 @@ public class StandbyStateManagementTest { // discovered by the ActiveStandbyFeature when the election handler initializes. StateManagementFeatureApi smf = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); smf = feature; logger.debug("testColdStandby stateManagementFeature.getResourceName(): {}", smf.getResourceName()); @@ -811,7 +813,7 @@ public class StandbyStateManagementTest { // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApi.impl.getList()) { + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); activeStandbyFeature = feature; logger.debug("testColdStandby activeStandbyFeature.getResourceName(): {}", @@ -924,7 +926,7 @@ public class StandbyStateManagementTest { // discovered by the ActiveStandbyFeature when the election handler initializes. StateManagementFeatureApi smf = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); smf = feature; logger.debug("testHotStandby1 stateManagementFeature.getResourceName(): {}", smf.getResourceName()); @@ -942,7 +944,7 @@ public class StandbyStateManagementTest { // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApi.impl.getList()) { + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); activeStandbyFeature = feature; logger.debug("testHotStandby1 activeStandbyFeature.getResourceName(): {}", @@ -1081,7 +1083,7 @@ public class StandbyStateManagementTest { // discovered by the ActiveStandbyFeature when the election handler initializes. StateManagementFeatureApi sm2 = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); sm2 = feature; logger.debug("testHotStandby2 stateManagementFeature.getResourceName(): {}", sm2.getResourceName()); @@ -1099,7 +1101,7 @@ public class StandbyStateManagementTest { // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApi.impl.getList()) { + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); activeStandbyFeature = feature; logger.debug("testHotStandby2 activeStandbyFeature.getResourceName(): {}", @@ -1238,7 +1240,7 @@ public class StandbyStateManagementTest { // discovered by the ActiveStandbyFeature when the election handler initializes. StateManagementFeatureApi sm = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); sm = feature; logger.debug("testLocking1 stateManagementFeature.getResourceName(): {}", sm.getResourceName()); @@ -1256,7 +1258,7 @@ public class StandbyStateManagementTest { // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApi.impl.getList()) { + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); activeStandbyFeature = feature; logger.debug("testLocking1 activeStandbyFeature.getResourceName(): {}", @@ -1486,7 +1488,7 @@ public class StandbyStateManagementTest { // discovered by the ActiveStandbyFeature when the election handler initializes. StateManagementFeatureApi sm = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); sm = feature; logger.debug("testLocking2 stateManagementFeature.getResourceName(): {}", sm.getResourceName()); @@ -1504,7 +1506,7 @@ public class StandbyStateManagementTest { // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature // that has been created. ActiveStandbyFeatureApi activeStandbyFeature = null; - for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApi.impl.getList()) { + for (ActiveStandbyFeatureApi feature : ActiveStandbyFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); activeStandbyFeature = feature; logger.debug("testLocking2 activeStandbyFeature.getResourceName(): {}", diff --git a/feature-controller-logging/src/main/java/org/onap/policy/drools/controller/logging/ControllerLoggingFeature.java b/feature-controller-logging/src/main/java/org/onap/policy/drools/controller/logging/ControllerLoggingFeature.java index d4ac090e..37857d39 100755 --- a/feature-controller-logging/src/main/java/org/onap/policy/drools/controller/logging/ControllerLoggingFeature.java +++ b/feature-controller-logging/src/main/java/org/onap/policy/drools/controller/logging/ControllerLoggingFeature.java @@ -29,6 +29,7 @@ import org.onap.policy.drools.features.PolicyEngineFeatureApi; import org.onap.policy.drools.protocol.configuration.ControllerConfiguration;
import org.onap.policy.drools.protocol.configuration.PdpdConfiguration;
import org.onap.policy.drools.system.PolicyController;
+import org.onap.policy.drools.system.PolicyControllerConstants;
import org.onap.policy.drools.system.PolicyEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -74,7 +75,8 @@ public class ControllerLoggingFeature public boolean afterDeliver(DroolsController controller, TopicSink sink, Object fact, String json,
boolean success) {
if (success) {
- Logger controllerLogger = LoggerFactory.getLogger(PolicyController.factory.get(controller).getName());
+ Logger controllerLogger = LoggerFactory
+ .getLogger(PolicyControllerConstants.getFactory().get(controller).getName());
controllerLogger.info("[OUT|{}|{}]{}{}", sink.getTopicCommInfrastructure(), sink.getTopic(),
System.lineSeparator(), json);
}
diff --git a/feature-controller-logging/src/test/java/org/onap/policy/drools/controller/logging/ControllerLoggingTest.java b/feature-controller-logging/src/test/java/org/onap/policy/drools/controller/logging/ControllerLoggingTest.java index 4fb6b91d..213ac493 100755 --- a/feature-controller-logging/src/test/java/org/onap/policy/drools/controller/logging/ControllerLoggingTest.java +++ b/feature-controller-logging/src/test/java/org/onap/policy/drools/controller/logging/ControllerLoggingTest.java @@ -39,12 +39,12 @@ import org.onap.policy.common.endpoints.event.comm.Topic; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink;
import org.onap.policy.drools.controller.DroolsController;
-import org.onap.policy.drools.controller.logging.ControllerLoggingFeature;
-import org.onap.policy.drools.properties.DroolsProperties;
+import org.onap.policy.drools.controller.DroolsControllerConstants;
+import org.onap.policy.drools.properties.DroolsPropertyConstants;
import org.onap.policy.drools.protocol.configuration.ControllerConfiguration;
import org.onap.policy.drools.protocol.configuration.PdpdConfiguration;
import org.onap.policy.drools.system.PolicyController;
-import org.onap.policy.drools.system.PolicyEngine;
+import org.onap.policy.drools.system.PolicyEngineConstants;
import org.onap.policy.drools.util.KieUtils;
/**
@@ -111,12 +111,13 @@ public class ControllerLoggingTest { JUNIT_KJAR_DRL_PATH, Paths.get(JUNIT_KMODULE_DRL_PATH).toFile());
controllerProps = new Properties();
- controllerProps.put(DroolsProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME);
- controllerProps.put(DroolsProperties.RULES_GROUPID, TEST_GROUP_ID);
- controllerProps.put(DroolsProperties.RULES_ARTIFACTID, TEST_ARTIFACT_ID);
- controllerProps.put(DroolsProperties.RULES_VERSION, TEST_VERSION);
+ controllerProps.put(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME);
+ controllerProps.put(DroolsPropertyConstants.RULES_GROUPID, TEST_GROUP_ID);
+ controllerProps.put(DroolsPropertyConstants.RULES_ARTIFACTID, TEST_ARTIFACT_ID);
+ controllerProps.put(DroolsPropertyConstants.RULES_VERSION, TEST_VERSION);
- policyController = PolicyEngine.manager.createPolicyController(TEST_CONTROLLER_NAME, controllerProps);
+ policyController = PolicyEngineConstants.getManager().createPolicyController(TEST_CONTROLLER_NAME,
+ controllerProps);
message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\",\"controllers\":"
+ "[{\"name\":\"test-controller\",\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","
@@ -167,7 +168,8 @@ public class ControllerLoggingTest { final ControllerLoggingFeature nlf = new ControllerLoggingFeature();
- DroolsController droolsController = DroolsController.factory.get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);
+ DroolsController droolsController =
+ DroolsControllerConstants.getFactory().get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);
NoopTopicSink sinkTopic = new NoopTopicSink(Arrays.asList(TEST_SERVER), TEST_TOPIC);
@@ -186,7 +188,8 @@ public class ControllerLoggingTest { final ControllerLoggingFeature nlf = new ControllerLoggingFeature();
- DroolsController droolsController = DroolsController.factory.get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);
+ DroolsController droolsController =
+ DroolsControllerConstants.getFactory().get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);
NoopTopicSink sinkTopic = new NoopTopicSink(Arrays.asList(TEST_SERVER), TEST_TOPIC);
@@ -203,7 +206,8 @@ public class ControllerLoggingTest { public void afterOnTopicEventSuccess() {
final ControllerLoggingFeature nlf = new ControllerLoggingFeature();
- nlf.afterOnTopicEvent(PolicyEngine.manager, pdpdNotification, CommInfrastructure.UEB, TEST_TOPIC, message);
+ nlf.afterOnTopicEvent(PolicyEngineConstants.getManager(), pdpdNotification, CommInfrastructure.UEB, TEST_TOPIC,
+ message);
assertEquals(1, events.size());
}
@@ -221,7 +225,8 @@ public class ControllerLoggingTest { config.setName("test-controller-2");
notification.setControllers(Arrays.asList(config));
- nlf.afterOnTopicEvent(PolicyEngine.manager, notification, CommInfrastructure.UEB, TEST_TOPIC, message);
+ nlf.afterOnTopicEvent(PolicyEngineConstants.getManager(), notification, CommInfrastructure.UEB, TEST_TOPIC,
+ message);
assertEquals(0, events.size());
}
diff --git a/feature-distributed-locking/src/main/java/org/onap/policy/distributed/locking/DistributedLockingFeature.java b/feature-distributed-locking/src/main/java/org/onap/policy/distributed/locking/DistributedLockingFeature.java index f162e1c4..d5e07a30 100644 --- a/feature-distributed-locking/src/main/java/org/onap/policy/distributed/locking/DistributedLockingFeature.java +++ b/feature-distributed-locking/src/main/java/org/onap/policy/distributed/locking/DistributedLockingFeature.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,7 +30,7 @@ import org.apache.commons.dbcp2.BasicDataSourceFactory; import org.onap.policy.common.utils.properties.exception.PropertyException; import org.onap.policy.drools.core.lock.PolicyResourceLockFeatureApi; import org.onap.policy.drools.features.PolicyEngineFeatureApi; -import org.onap.policy.drools.persistence.SystemPersistence; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,7 +58,7 @@ public class DistributedLockingFeature implements PolicyEngineFeatureApi, Policy private BasicDataSource dataSource; /** - * UUID. + * UUID. */ private static final UUID uuid = UUID.randomUUID(); @@ -80,7 +80,7 @@ public class DistributedLockingFeature implements PolicyEngineFeatureApi, Policy TargetLock lock = new TargetLock(resourceId, uuid, owner, dataSource); - return (lock.refresh(holdSec) ? OperResult.OPER_ACCEPTED : OperResult.OPER_DENIED); + return (lock.refresh(holdSec) ? OperResult.OPER_ACCEPTED : OperResult.OPER_DENIED); } @Override @@ -108,8 +108,8 @@ public class DistributedLockingFeature implements PolicyEngineFeatureApi, Policy public boolean afterStart(PolicyEngine engine) { try { - this.lockProps = new DistributedLockingProperties( - SystemPersistence.manager.getProperties(DistributedLockingFeature.CONFIGURATION_PROPERTIES_NAME)); + this.lockProps = new DistributedLockingProperties(SystemPersistenceConstants.getManager() + .getProperties(DistributedLockingFeature.CONFIGURATION_PROPERTIES_NAME)); this.dataSource = makeDataSource(); } catch (PropertyException e) { logger.error("DistributedLockingFeature feature properies have not been loaded", e); @@ -130,7 +130,7 @@ public class DistributedLockingFeature implements PolicyEngineFeatureApi, Policy /** * Make data source. - * + * * @return a new, pooled data source * @throws Exception exception */ diff --git a/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/DistributedLockingFeatureTest.java b/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/DistributedLockingFeatureTest.java index 90e8bfc0..68a5a31b 100644 --- a/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/DistributedLockingFeatureTest.java +++ b/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/DistributedLockingFeatureTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.utils.properties.exception.PropertyException; -import org.onap.policy.drools.persistence.SystemPersistence; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; /** * Partially tests DistributedLockingFeature; most of the methods are tested via @@ -43,7 +43,7 @@ public class DistributedLockingFeatureTest { @BeforeClass public static void setUpBeforeClass() throws Exception { - SystemPersistence.manager.setConfigurationDir("src/test/resources"); + SystemPersistenceConstants.getManager().setConfigurationDir("src/test/resources"); } @Before diff --git a/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/TargetLockTest.java b/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/TargetLockTest.java index 6fa1febb..84eba6b6 100644 --- a/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/TargetLockTest.java +++ b/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/TargetLockTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * feature-distributed-locking * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.drools.core.lock.PolicyResourceLockFeatureApi.OperResult; -import org.onap.policy.drools.persistence.SystemPersistence; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -64,7 +64,7 @@ public class TargetLockTest { public static void setup() { getDbConnection(); createTable(); - SystemPersistence.manager.setConfigurationDir("src/test/resources"); + SystemPersistenceConstants.getManager().setConfigurationDir("src/test/resources"); distLockFeat = new DistributedLockingFeature(); distLockFeat.afterStart(null); } diff --git a/feature-eelf/src/test/java/org/onap/policy/drools/eelf/test/EElfTest.java b/feature-eelf/src/test/java/org/onap/policy/drools/eelf/test/EElfTest.java index 5a1645a0..271fd4a5 100644 --- a/feature-eelf/src/test/java/org/onap/policy/drools/eelf/test/EElfTest.java +++ b/feature-eelf/src/test/java/org/onap/policy/drools/eelf/test/EElfTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,19 +24,16 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import ch.qos.logback.classic.LoggerContext; - import com.att.eelf.configuration.Configuration; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFLogger.Level; import com.att.eelf.configuration.EELFManager; - import java.util.ArrayList; import java.util.List; - import org.junit.Test; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.drools.eelf.EelfFeature; -import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.system.PolicyEngineConstants; import org.onap.policy.drools.utils.logging.LoggerUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,12 +55,12 @@ public class EElfTest { /** * Get all loggers. - * + * * @return list of all loggers */ protected List<String> loggers() { List<String> loggers = new ArrayList<String>(); - LoggerContext context = + LoggerContext context = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory(); for (org.slf4j.Logger logger: context.getLoggerList()) { loggers.add(logger.getName()); @@ -74,7 +71,7 @@ public class EElfTest { /** * Assert Log Levels are the same between an EELF Logger and an SLF4J Logger. - * + * * @param eelfLogger EELF Logger * @param slf4jLogger SLF4J Logger */ @@ -108,7 +105,7 @@ public class EElfTest { /* set up eelf throuth common loggings library */ EelfFeature feature = new EelfFeature(); - feature.beforeBoot(PolicyEngine.manager, null); + feature.beforeBoot(PolicyEngineConstants.getManager(), null); loggers = loggers(); assertTrue(loggers.contains(Configuration.DEBUG_LOGGER_NAME)); @@ -118,7 +115,7 @@ public class EElfTest { final EELFLogger eelfAuditLogger = EELFManager.getInstance().getAuditLogger(); final Logger slf4jAuditLogger = org.slf4j.LoggerFactory.getLogger(Configuration.AUDIT_LOGGER_NAME); - org.onap.policy.common.logging.flexlogger.Logger flexLogger = + org.onap.policy.common.logging.flexlogger.Logger flexLogger = FlexLogger.getLogger(EElfTest.class, true); /* generate an error entry */ diff --git a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java index 1a4dab6b..b1b28f79 100644 --- a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java +++ b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java @@ -30,11 +30,6 @@ import org.onap.policy.common.capabilities.Startable; public interface HealthCheck extends Startable { /** - * Healthcheck Monitor. - */ - public static final HealthCheck monitor = new HealthCheckMonitor(); - - /** * Healthcheck Report. */ public static class Report { diff --git a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckConstants.java b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckConstants.java new file mode 100644 index 00000000..70b241dd --- /dev/null +++ b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckConstants.java @@ -0,0 +1,36 @@ +/* + * ============LICENSE_START======================================================= + * feature-healthcheck + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.healthcheck; + +import lombok.Getter; + +public class HealthCheckConstants { + + /** + * Healthcheck Monitor. + */ + @Getter + private static final HealthCheck manager = new HealthCheckManager(); + + private HealthCheckConstants() { + // do nothing + } +} diff --git a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckFeature.java b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckFeature.java index af638c75..961f4a1d 100644 --- a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckFeature.java +++ b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckFeature.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,7 +33,7 @@ public class HealthCheckFeature implements PolicyEngineFeatureApi { /** * Logger. */ - private static Logger logger = LoggerFactory.getLogger(HealthCheckFeature.class); + private static Logger logger = LoggerFactory.getLogger(HealthCheckFeature.class); /** * Properties Configuration Name. @@ -48,7 +48,7 @@ public class HealthCheckFeature implements PolicyEngineFeatureApi { @Override public boolean afterStart(PolicyEngine engine) { try { - getMonitor().start(); + getManager().start(); } catch (IllegalStateException e) { logger.error("Healthcheck Monitor cannot be started", e); } @@ -59,7 +59,7 @@ public class HealthCheckFeature implements PolicyEngineFeatureApi { @Override public boolean afterShutdown(PolicyEngine engine) { try { - getMonitor().stop(); + getManager().stop(); } catch (IllegalStateException e) { logger.error("Healthcheck Monitor cannot be stopped", e); } @@ -69,11 +69,11 @@ public class HealthCheckFeature implements PolicyEngineFeatureApi { /** * Gets the monitor. - * - * @return the healthcheck monitor + * + * @return the healthcheck manager */ - public HealthCheck getMonitor() { - return HealthCheck.monitor; + public HealthCheck getManager() { + return HealthCheckConstants.getManager(); } } diff --git a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckMonitor.java b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckManager.java index cca56e01..f0b9313a 100644 --- a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckMonitor.java +++ b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckManager.java @@ -30,8 +30,9 @@ import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactory; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; -import org.onap.policy.drools.persistence.SystemPersistence; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.system.PolicyEngineConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,12 +40,12 @@ import org.slf4j.LoggerFactory; /** * Healthcheck Monitor. */ -public class HealthCheckMonitor implements HealthCheck { +public class HealthCheckManager implements HealthCheck { /** * Logger. */ - private static Logger logger = LoggerFactory.getLogger(HealthCheckMonitor.class); + private static Logger logger = LoggerFactory.getLogger(HealthCheckManager.class); /** * Attached http servers. @@ -233,7 +234,7 @@ public class HealthCheckMonitor implements HealthCheck { // the following methods may be overridden by junit tests protected PolicyEngine getEngineManager() { - return PolicyEngine.manager; + return PolicyEngineConstants.getManager(); } protected HttpServletServerFactory getServerFactory() { @@ -245,6 +246,6 @@ public class HealthCheckMonitor implements HealthCheck { } protected Properties getPersistentProperties(String propertyName) { - return SystemPersistence.manager.getProperties(propertyName); + return SystemPersistenceConstants.getManager().getProperties(propertyName); } } diff --git a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/RestHealthCheck.java b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/RestHealthCheck.java index 5047cb26..954a2c55 100644 --- a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/RestHealthCheck.java +++ b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/RestHealthCheck.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * feature-healthcheck * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -56,24 +56,24 @@ public class RestHealthCheck { @Path("healthcheck") @Produces(MediaType.APPLICATION_JSON) @ApiOperation( - value = "Perform a system healthcheck", + value = "Perform a system healthcheck", notes = "Provides healthy status of the PDP-D plus the components defined in its " + "configuration by using a REST interface", response = Reports.class ) - public Response healthcheck() { - return Response.status(Response.Status.OK).entity(HealthCheck.monitor.healthCheck()).build(); + public Response healthcheck() { + return Response.status(Response.Status.OK).entity(HealthCheckConstants.getManager().healthCheck()).build(); } @GET @Path("healthcheck/configuration") @Produces(MediaType.APPLICATION_JSON) @ApiOperation( - value = "Configuration", + value = "Configuration", notes = "Provides the Healthcheck server configuration and monitored REST clients", response = HealthCheck.class ) - public HealthCheck configuration() { - return HealthCheck.monitor; + public HealthCheck configuration() { + return HealthCheckConstants.getManager(); } } diff --git a/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java b/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java index 42d77f26..4d93af23 100644 --- a/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java +++ b/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * feature-healthcheck * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,8 +42,8 @@ import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.drools.healthcheck.HealthCheck.Report; import org.onap.policy.drools.healthcheck.HealthCheck.Reports; -import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; +import org.onap.policy.drools.system.PolicyEngineConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,11 +54,13 @@ public class HealthCheckFeatureTest { */ private static final String HEALTH_CHECK_PROPERTIES_FILE = "feature-healthcheck.properties"; - private static final Path healthCheckPropsPath = Paths - .get(SystemPersistence.manager.getConfigurationPath().toString(), HEALTH_CHECK_PROPERTIES_FILE); + private static final Path healthCheckPropsPath = + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), + HEALTH_CHECK_PROPERTIES_FILE); - private static final Path healthCheckPropsBackupPath = Paths.get( - SystemPersistence.manager.getConfigurationPath().toString(), HEALTH_CHECK_PROPERTIES_FILE + ".bak"); + private static final Path healthCheckPropsBackupPath = + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), + HEALTH_CHECK_PROPERTIES_FILE + ".bak"); private static final String EXPECTED = "expected exception"; @@ -131,13 +133,13 @@ public class HealthCheckFeatureTest { public void test() throws IOException, InterruptedException { HealthCheckFeature feature = new HealthCheckFeature(); - feature.afterStart(PolicyEngine.manager); + feature.afterStart(PolicyEngineConstants.getManager()); if (!NetworkUtil.isTcpPortOpen("localhost", 7777, 5, 10000L)) { throw new IllegalStateException("cannot connect to port " + 7777); } - Reports reports = HealthCheck.monitor.healthCheck(); + Reports reports = HealthCheckConstants.getManager().healthCheck(); assertTrue(reports.getDetails().size() > 0); @@ -150,7 +152,7 @@ public class HealthCheckFeatureTest { } } - feature.afterShutdown(PolicyEngine.manager); + feature.afterShutdown(PolicyEngineConstants.getManager()); } @@ -197,7 +199,7 @@ public class HealthCheckFeatureTest { File origPropsFile = new File(healthCheckPropsPath.toString()); File backupPropsFile = new File(healthCheckPropsBackupPath.toString()); - Path configDir = Paths.get(SystemPersistence.DEFAULT_CONFIGURATION_DIR); + Path configDir = Paths.get(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR); try { @@ -243,7 +245,7 @@ public class HealthCheckFeatureTest { } @Override - public HealthCheck getMonitor() { + public HealthCheck getManager() { return checker; } diff --git a/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckTest.java b/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckTest.java index 2bf1cca5..62c6c951 100644 --- a/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckTest.java +++ b/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckTest.java @@ -70,7 +70,7 @@ public class HealthCheckTest { private List<HttpServletServer> servers; private List<HttpClient> clients; private PolicyEngine engineMgr; - private HealthCheckMonitor monitor; + private HealthCheckManager monitor; /** * Initializes the object to be tested. @@ -310,23 +310,23 @@ public class HealthCheckTest { @Test public void testHealthCheckMonitor_GetEngineManager() { - assertNotNull(new HealthCheckMonitor().getEngineManager()); + assertNotNull(new HealthCheckManager().getEngineManager()); } @Test public void testHealthCheckMonitor_GetServerFactory() { - assertNotNull(new HealthCheckMonitor().getServerFactory()); + assertNotNull(new HealthCheckManager().getServerFactory()); } @Test public void testHealthCheckMonitor_GetClientFactory() { - assertNotNull(new HealthCheckMonitor().getClientFactory()); + assertNotNull(new HealthCheckManager().getClientFactory()); } /** * Monitor with overrides. */ - private class HealthCheckMonitorImpl extends HealthCheckMonitor { + private class HealthCheckMonitorImpl extends HealthCheckManager { @Override protected PolicyEngine getEngineManager() { diff --git a/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFsm.java b/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFsm.java index 67f5467b..36d2a545 100644 --- a/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFsm.java +++ b/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFsm.java @@ -45,7 +45,8 @@ import org.onap.policy.common.gson.annotation.GsonJsonIgnore; import org.onap.policy.common.utils.coder.StandardCoderObject; import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.drools.controller.DroolsController; -import org.onap.policy.drools.persistence.SystemPersistence; +import org.onap.policy.drools.controller.DroolsControllerConstants; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.drools.system.PolicyController; import org.onap.policy.models.pdp.concepts.PdpResponseDetails; import org.onap.policy.models.pdp.concepts.PdpStateChange; @@ -116,7 +117,7 @@ public class LifecycleFsm implements Startable { * Constructor. */ public LifecycleFsm() { - this.properties = SystemPersistence.manager.getProperties(CONFIGURATION_PROPERTIES_NAME); + this.properties = SystemPersistenceConstants.getManager().getProperties(CONFIGURATION_PROPERTIES_NAME); scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); @@ -305,7 +306,7 @@ public class LifecycleFsm implements Startable { private boolean startTimers() { statusTask = - this.scheduler.scheduleAtFixedRate(() -> status(), 0, statusTimerSeconds, TimeUnit.SECONDS); + this.scheduler.scheduleAtFixedRate(this::status, 0, statusTimerSeconds, TimeUnit.SECONDS); return !statusTask.isCancelled() && !statusTask.isDone(); } @@ -381,7 +382,7 @@ public class LifecycleFsm implements Startable { private List<ToscaPolicyTypeIdentifier> getCapabilities() { List<ToscaPolicyTypeIdentifier> capabilities = new ArrayList<>(); - for (DroolsController dc : DroolsController.factory.inventory()) { + for (DroolsController dc : DroolsControllerConstants.getFactory().inventory()) { if (!dc.isBrained()) { continue; } diff --git a/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleStateRunning.java b/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleStateRunning.java index d5820d08..c5ea44b2 100644 --- a/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleStateRunning.java +++ b/feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleStateRunning.java @@ -42,6 +42,10 @@ public abstract class LifecycleStateRunning extends LifecycleStateDefault { private static final Logger logger = LoggerFactory.getLogger(LifecycleStateRunning.class); + protected LifecycleStateRunning(LifecycleFsm manager) { + super(manager); + } + protected abstract boolean stateChangeToPassive(@NonNull PdpStateChange change); protected abstract boolean stateChangeToActive(@NonNull PdpStateChange change); @@ -50,10 +54,6 @@ public abstract class LifecycleStateRunning extends LifecycleStateDefault { protected abstract boolean undeployPolicy(@NonNull PolicyController controller, @NonNull ToscaPolicy policy); - protected LifecycleStateRunning(LifecycleFsm manager) { - super(manager); - } - @Override public boolean start() { logger.warn("{}: start", this); diff --git a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/ControllerSupport.java b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/ControllerSupport.java index 3a3434ac..e82eb42b 100644 --- a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/ControllerSupport.java +++ b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/ControllerSupport.java @@ -27,8 +27,9 @@ import java.util.Properties; import lombok.Getter; import lombok.NonNull; import org.kie.api.builder.ReleaseId; -import org.onap.policy.drools.properties.DroolsProperties; +import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyControllerConstants; import org.onap.policy.drools.util.KieUtils; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; @@ -75,27 +76,27 @@ public class ControllerSupport { Properties controllerProps = new Properties(); - controllerProps.put(DroolsProperties.PROPERTY_CONTROLLER_NAME, name); - controllerProps.put(DroolsProperties.PROPERTY_CONTROLLER_POLICY_TYPES, getPolicyType()); - controllerProps.put(DroolsProperties.RULES_GROUPID, coordinates.getGroupId()); - controllerProps.put(DroolsProperties.RULES_ARTIFACTID, coordinates.getArtifactId()); - controllerProps.put(DroolsProperties.RULES_VERSION, coordinates.getVersion()); + controllerProps.put(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, name); + controllerProps.put(DroolsPropertyConstants.PROPERTY_CONTROLLER_POLICY_TYPES, getPolicyType()); + controllerProps.put(DroolsPropertyConstants.RULES_GROUPID, coordinates.getGroupId()); + controllerProps.put(DroolsPropertyConstants.RULES_ARTIFACTID, coordinates.getArtifactId()); + controllerProps.put(DroolsPropertyConstants.RULES_VERSION, coordinates.getVersion()); - return PolicyController.factory.build(name, controllerProps); + return PolicyControllerConstants.getFactory().build(name, controllerProps); } /** * Destroy the echo controller. */ public void destroyController() { - PolicyController.factory.destroy(name); + PolicyControllerConstants.getFactory().destroy(name); } /** * Get controller. */ public PolicyController getController() { - return PolicyController.factory.get(name); + return PolicyControllerConstants.getFactory().get(name); } /** @@ -109,7 +110,7 @@ public class ControllerSupport { * Get facts. */ public <T> List<T> getFacts(Class<T> clazz) { - return PolicyController.factory.get(name) + return PolicyControllerConstants.getFactory().get(name) .getDrools() .facts(SESSION_NAME, clazz); } diff --git a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateRunningTest.java b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateRunningTest.java index 25cce3a9..8ac47e55 100644 --- a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateRunningTest.java +++ b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateRunningTest.java @@ -25,7 +25,7 @@ import java.nio.file.Files; import java.nio.file.Paths; import org.junit.AfterClass; import org.junit.BeforeClass; -import org.onap.policy.drools.persistence.SystemPersistence; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.drools.utils.logging.LoggerUtil; public abstract class LifecycleStateRunningTest { @@ -42,7 +42,7 @@ public abstract class LifecycleStateRunningTest { LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); LoggerUtil.setLevel("org.onap.policy.common.endpoints", "WARN"); LoggerUtil.setLevel("org.onap.policy.drools", "INFO"); - SystemPersistence.manager.setConfigurationDir("target/test-classes"); + SystemPersistenceConstants.getManager().setConfigurationDir("target/test-classes"); controllerSupport.createController(); } @@ -52,11 +52,11 @@ public abstract class LifecycleStateRunningTest { @AfterClass public static void tearDown() { try { - Files.deleteIfExists(Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), + Files.deleteIfExists(Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), CONTROLLER_NAME + "-controller.properties.bak")); } catch (IOException e) { ; } - SystemPersistence.manager.setConfigurationDir(null); + SystemPersistenceConstants.getManager().setConfigurationDir(null); } } diff --git a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateTerminatedTest.java b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateTerminatedTest.java index 50c4f1a7..353525d6 100644 --- a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateTerminatedTest.java +++ b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateTerminatedTest.java @@ -33,7 +33,7 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.utils.network.NetworkUtil; -import org.onap.policy.drools.persistence.SystemPersistence; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.drools.utils.logging.LoggerUtil; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpUpdate; @@ -47,13 +47,13 @@ public class LifecycleStateTerminatedTest { @BeforeClass public static void setUp() { - SystemPersistence.manager.setConfigurationDir("src/test/resources"); + SystemPersistenceConstants.getManager().setConfigurationDir("src/test/resources"); LoggerUtil.setLevel("org.onap.policy.common.endpoints", "WARN"); } @AfterClass public static void tearDown() { - SystemPersistence.manager.setConfigurationDir(null); + SystemPersistenceConstants.getManager().setConfigurationDir(null); } @Test diff --git a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateUnsupportedTest.java b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateUnsupportedTest.java index 01efca32..14da6ab0 100644 --- a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateUnsupportedTest.java +++ b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateUnsupportedTest.java @@ -26,7 +26,7 @@ import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import org.onap.policy.drools.persistence.SystemPersistence; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpUpdate; @@ -39,12 +39,12 @@ public abstract class LifecycleStateUnsupportedTest { @BeforeClass public static void setUp() { - SystemPersistence.manager.setConfigurationDir("src/test/resources"); + SystemPersistenceConstants.getManager().setConfigurationDir("src/test/resources"); } @AfterClass public static void tearDown() { - SystemPersistence.manager.setConfigurationDir(null); + SystemPersistenceConstants.getManager().setConfigurationDir(null); } public LifecycleStateUnsupportedTest(LifecycleState state) { diff --git a/feature-lifecycle/src/test/java/org/onap/policy/drools/server/restful/RestLifecycleManagerTest.java b/feature-lifecycle/src/test/java/org/onap/policy/drools/server/restful/RestLifecycleManagerTest.java index 92269167..da7435f3 100644 --- a/feature-lifecycle/src/test/java/org/onap/policy/drools/server/restful/RestLifecycleManagerTest.java +++ b/feature-lifecycle/src/test/java/org/onap/policy/drools/server/restful/RestLifecycleManagerTest.java @@ -33,7 +33,7 @@ import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; import org.onap.policy.common.utils.network.NetworkUtil; -import org.onap.policy.drools.persistence.SystemPersistence; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.models.pdp.enums.PdpState; /** @@ -49,7 +49,7 @@ public class RestLifecycleManagerTest { HttpServletServerFactoryInstance.getServerFactory().destroy(); HttpClientFactoryInstance.getClientFactory().destroy(); - SystemPersistence.manager.setConfigurationDir("target/test-classes"); + SystemPersistenceConstants.getManager().setConfigurationDir("target/test-classes"); HttpClientFactoryInstance.getClientFactory().build( BusTopicParams.builder() diff --git a/feature-mdc-filters/src/main/java/org/onap/policy/drools/mdc/filters/MdcFilterFeature.java b/feature-mdc-filters/src/main/java/org/onap/policy/drools/mdc/filters/MdcFilterFeature.java index fecdbe91..0f6c3d72 100755 --- a/feature-mdc-filters/src/main/java/org/onap/policy/drools/mdc/filters/MdcFilterFeature.java +++ b/feature-mdc-filters/src/main/java/org/onap/policy/drools/mdc/filters/MdcFilterFeature.java @@ -29,7 +29,7 @@ import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.common.endpoints.features.NetLoggerFeatureApi;
import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
import org.onap.policy.drools.features.PolicyControllerFeatureApi;
-import org.onap.policy.drools.persistence.SystemPersistence;
+import org.onap.policy.drools.persistence.SystemPersistenceConstants;
import org.onap.policy.drools.system.PolicyController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -74,7 +74,7 @@ public class MdcFilterFeature implements NetLoggerFeatureApi, PolicyControllerFe * @return the properties for this feature.
*/
protected Properties getFeatureProps() {
- return SystemPersistence.manager.getProperties(FEATURE_NAME);
+ return SystemPersistenceConstants.getManager().getProperties(FEATURE_NAME);
}
/**
diff --git a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingFeature.java b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingFeature.java index c52a8a97..d4704afe 100644 --- a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingFeature.java +++ b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingFeature.java @@ -35,8 +35,9 @@ import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.features.DroolsControllerFeatureApi; import org.onap.policy.drools.features.PolicyControllerFeatureApi; import org.onap.policy.drools.features.PolicyEngineFeatureApi; -import org.onap.policy.drools.persistence.SystemPersistence; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyControllerConstants; import org.onap.policy.drools.system.PolicyEngine; import org.onap.policy.drools.util.FeatureEnabledChecker; import org.slf4j.Logger; @@ -386,7 +387,7 @@ public class PoolingFeature implements PolicyEngineFeatureApi, PolicyControllerF * @return the properties for the specified feature */ protected Properties getProperties(String featName) { - return SystemPersistence.manager.getProperties(featName); + return SystemPersistenceConstants.getManager().getProperties(featName); } /** @@ -410,7 +411,7 @@ public class PoolingFeature implements PolicyEngineFeatureApi, PolicyControllerF * @return the policy controller associated with a drools controller */ protected PolicyController getController(DroolsController droolsController) { - return PolicyController.factory.get(droolsController); + return PolicyControllerConstants.getFactory().get(droolsController); } /** diff --git a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingManagerImpl.java b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingManagerImpl.java index b8fb6410..b2966101 100644 --- a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingManagerImpl.java +++ b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingManagerImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -46,7 +46,7 @@ import org.onap.policy.drools.pooling.state.QueryState; import org.onap.policy.drools.pooling.state.StartState; import org.onap.policy.drools.pooling.state.State; import org.onap.policy.drools.pooling.state.StateTimerTask; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants; import org.onap.policy.drools.system.PolicyController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -120,7 +120,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Current state. - * + * * <p>This uses a finite state machine, wherein the state object contains all of the data * relevant to that state. Each state object has a process() method, specific to each * type of {@link Message} subclass. The method returns the next state object, or @@ -182,7 +182,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Should only be used by junit tests. - * + * * @return the current state */ protected State getCurrent() { @@ -208,7 +208,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Makes properties for configuring extractors. - * + * * @param controller the controller for which the extractors will be configured * @param source properties from which to get the extractor properties * @return extractor properties @@ -324,7 +324,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Changes the finite state machine to a new state, provided the new state is not * {@code null}. - * + * * @param newState new state, or {@code null} if to remain unchanged */ private void changeState(State newState) { @@ -340,7 +340,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Sets the server-side filter for the internal topic. - * + * * @param filter new filter to be used */ private void setFilter(Map<String, Object> filter) { @@ -402,7 +402,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Handles an event from the internal topic. - * + * * @param commType comm infrastructure * @param topic2 topic * @param event event @@ -425,11 +425,11 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { * Called by the PolicyController before it offers the event to the DroolsController. * If the controller is locked, then it isn't processing events. However, they still * need to be forwarded, thus in that case, they are decoded and forwarded. - * + * * <p>On the other hand, if the controller is not locked, then we just return immediately * and let {@link #beforeInsert(Object, String, String, Object) beforeInsert()} handle * it instead, as it already has the decoded message. - * + * * @param protocol protocol * @param topic2 topic * @param event event @@ -448,7 +448,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Called by the DroolsController before it inserts the event into the rule engine. - * + * * @param protocol protocol * @param topic2 topic * @param event original event text, as received from the Bus @@ -468,7 +468,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Handles an event from an external topic. - * + * * @param protocol protocol * @param topic2 topic * @param event event @@ -503,7 +503,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Handles an event from an external topic. - * + * * @param event event * @return {@code true} if the event was handled, {@code false} if the invoker should * handle it @@ -523,7 +523,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Handles a {@link Forward} event, possibly forwarding it again. - * + * * @param event event * @return {@code true} if the event was handled, {@code false} if the invoker should * handle it @@ -564,7 +564,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Extract the request id from an event object. - * + * * @param event the event object, or {@code null} * @return the event's request id, or {@code null} if it can't be extracted */ @@ -579,7 +579,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Decodes an event from a String into an event Object. - * + * * @param topic2 topic * @param event event * @return the decoded event object, or {@code null} if it can't be decoded @@ -609,7 +609,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Makes a {@link Forward}, and validates its contents. - * + * * @param protocol protocol * @param topic2 topic * @param event event @@ -645,7 +645,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Injects an event into the controller. - * + * * @param event event */ private void inject(Forward event) { @@ -664,7 +664,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { * Handles an event from the internal topic. This uses reflection to identify the * appropriate process() method to invoke, based on the type of Message that was * decoded. - * + * * @param event the serialized {@link Message} read from the internal topic */ private void handleInternal(String event) { @@ -746,7 +746,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Constructor. - * + * * @param task task to execute when this timer runs */ public TimerAction(StateTimerTask task) { @@ -763,14 +763,14 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { } } } - + /* * The remaining methods may be overridden by junit tests. */ /** * Creates object extractors. - * + * * @param props properties used to configure the extractors * @return a new set of extractors */ @@ -781,7 +781,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Creates a DMaaP manager. - * + * * @param topic name of the internal DMaaP topic * @return a new DMaaP manager * @throws PoolingFeatureException if an error occurs @@ -792,7 +792,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Creates a scheduled thread pool. - * + * * @return a new scheduled thread pool */ protected ScheduledThreadPoolExecutor makeScheduler() { @@ -801,18 +801,19 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { /** * Determines if the event can be decoded. - * + * * @param drools drools controller * @param topic topic on which the event was received * @return {@code true} if the event can be decoded, {@code false} otherwise */ protected boolean canDecodeEvent(DroolsController drools, String topic) { - return EventProtocolCoder.manager.isDecodingSupported(drools.getGroupId(), drools.getArtifactId(), topic); + return EventProtocolCoderConstants.getManager().isDecodingSupported(drools.getGroupId(), drools.getArtifactId(), + topic); } /** * Decodes the event. - * + * * @param drools drools controller * @param topic topic on which the event was received * @param event event text to be decoded @@ -822,6 +823,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener { * @throws IllegalStateException illegal state */ protected Object decodeEventWrapper(DroolsController drools, String topic, String event) { - return EventProtocolCoder.manager.decode(drools.getGroupId(), drools.getArtifactId(), topic, event); + return EventProtocolCoderConstants.getManager().decode(drools.getGroupId(), drools.getArtifactId(), topic, + event); } } diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java index e280d6a5..cc826905 100644 --- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java +++ b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java @@ -48,6 +48,7 @@ import org.onap.policy.drools.core.PolicySession; import org.onap.policy.drools.core.PolicySessionFeatureApi; import org.onap.policy.drools.features.PolicyEngineFeatureApi; import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyControllerConstants; import org.onap.policy.drools.system.PolicyEngine; import org.onap.policy.drools.utils.PropertyUtil; import org.slf4j.Logger; @@ -65,7 +66,7 @@ import org.slf4j.LoggerFactory; public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngineFeatureApi { private static final Logger logger = LoggerFactory.getLogger(PersistenceFeature.class); - + /** KieService factory. */ private KieServices kieSvcFact; @@ -75,7 +76,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine /** Whether or not the SessionInfo records should be cleaned out. */ private boolean sessInfoCleaned; - /** SessionInfo timeout, in milli-seconds, as read from + /** SessionInfo timeout, in milli-seconds, as read from * {@link #persistProps}. */ private long sessionInfoTimeoutMs; @@ -103,7 +104,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine return (ContainerAdjunct) rval; } - /** + /** * {@inheritDoc}. **/ @Override @@ -111,7 +112,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine return 1; } - /** + /** * {@inheritDoc}. **/ @Override @@ -146,7 +147,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine return null; } - /** + /** * {@inheritDoc}. **/ @Override @@ -159,7 +160,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine return null; } - /** + /** * {@inheritDoc}. **/ @Override @@ -172,7 +173,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine } } - /** + /** * {@inheritDoc}. **/ @Override @@ -185,7 +186,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine } } - /** + /** * {@inheritDoc}. **/ @Override @@ -193,7 +194,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine return false; } - /** + /** * {@inheritDoc}. **/ @Override @@ -205,7 +206,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine return false; } - /** + /** * {@inheritDoc}. **/ @Override @@ -217,7 +218,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine return false; } - /** + /** * {@inheritDoc}. **/ @Override @@ -673,7 +674,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine /** * Get thread name. - * + * * @return the String to use as the thread name */ private String getThreadName() { return "Session " + session.getFullName() + " (persistent)"; @@ -683,7 +684,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine /* 'ThreadModel' interface */ /*=========================*/ - /** + /** * {@inheritDoc}. **/ @Override @@ -691,7 +692,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine thread.start(); } - /** + /** * {@inheritDoc}. **/ @Override @@ -714,7 +715,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine } } - /** + /** * {@inheritDoc}. **/ @Override @@ -727,7 +728,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine /* 'Runnable' interface */ /*======================*/ - /** + /** * {@inheritDoc}. **/ @Override @@ -926,7 +927,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine * @return the container's controller */ protected PolicyController getPolicyController(PolicyContainer container) { - return PolicyController.factory.get(container.getGroupId(), container.getArtifactId()); + return PolicyControllerConstants.getFactory().get(container.getGroupId(), container.getArtifactId()); } /** @@ -936,7 +937,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine public static class PersistenceFeatureException extends RuntimeException { private static final long serialVersionUID = 1L; - /** + /** * Constructor. * */ public PersistenceFeatureException(Exception ex) { diff --git a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeature.java b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeature.java index d8468b56..7d5ba512 100644 --- a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeature.java +++ b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeature.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -43,7 +43,7 @@ import org.slf4j.LoggerFactory; * a separate optional feature. */ -public class StateManagementFeature implements StateManagementFeatureApi, +public class StateManagementFeature implements StateManagementFeatureApi, PolicySessionFeatureApi, PolicyEngineFeatureApi { // get an instance of logger private static final Logger logger = @@ -187,7 +187,7 @@ public class StateManagementFeature implements StateManagementFeatureApi, /** * {@inheritDoc}. - * + * * @return true if locked or false if failed */ @Override @@ -203,7 +203,7 @@ public class StateManagementFeature implements StateManagementFeatureApi, /** * {@inheritDoc}. - * + * * @throws Exception exception */ @Override @@ -219,8 +219,8 @@ public class StateManagementFeature implements StateManagementFeatureApi, /** * {@inheritDoc}. - * - * @throws Exception exception + * + * @throws Exception exception */ @Override public boolean isLocked() { @@ -229,19 +229,19 @@ public class StateManagementFeature implements StateManagementFeatureApi, @Override public int getSequenceNumber() { - return SEQ_NUM; + return StateManagementFeatureApiConstants.SEQ_NUM; } /** * Read in the properties and initialize the StateManagementProperties. */ private static void initializeProperties(String configDir) { - //Get the state management properties + //Get the state management properties try { Properties props = PropertyUtil.getProperties(configDir + "/feature-state-management.properties"); StateManagementProperties.initProperties(props); - logger.info("initializeProperties: resourceName= {}", + logger.info("initializeProperties: resourceName= {}", StateManagementProperties.getProperty(StateManagementProperties.NODE_NAME)); } catch (IOException e1) { logger.error("initializeProperties", e1); diff --git a/feature-state-management/src/test/java/org/onap/policy/drools/statemanagement/test/StateManagementTest.java b/feature-state-management/src/test/java/org/onap/policy/drools/statemanagement/test/StateManagementTest.java index 327bb166..86125069 100644 --- a/feature-state-management/src/test/java/org/onap/policy/drools/statemanagement/test/StateManagementTest.java +++ b/feature-state-management/src/test/java/org/onap/policy/drools/statemanagement/test/StateManagementTest.java @@ -44,6 +44,7 @@ import org.onap.policy.drools.statemanagement.DbAudit; import org.onap.policy.drools.statemanagement.IntegrityMonitorRestManager; import org.onap.policy.drools.statemanagement.RepositoryAudit; import org.onap.policy.drools.statemanagement.StateManagementFeatureApi; +import org.onap.policy.drools.statemanagement.StateManagementFeatureApiConstants; import org.onap.policy.drools.statemanagement.StateManagementProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -115,7 +116,7 @@ public class StateManagementTest { .getProperty(StateManagementProperties.NODE_NAME); StateManagementFeatureApi stateManagementFeature = null; - for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApiConstants.getImpl().getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); stateManagementFeature = feature; logger.debug("testStateManagementOperation stateManagementFeature.getResourceName(): " diff --git a/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransaction.java b/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransaction.java index 03a0e4b7..0a4ef931 100644 --- a/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransaction.java +++ b/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransaction.java @@ -25,13 +25,6 @@ import org.onap.policy.drools.system.PolicyController; /** TestTransaction interface. */ public interface TestTransaction { - public static final String TT_FPC = "TT.FPC"; - public static final String TT_COUNTER = "$ttc"; - public static final String TT_UUID = "43868e59-d1f3-43c2-bd6f-86f89a61eea5"; - public static long DEFAULT_TT_TASK_SLEEP = 20000; - - public static final TestTransaction manager = new TtImpl(); - /** * register a controller for monitoring test transactions. * diff --git a/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransactionConstants.java b/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransactionConstants.java new file mode 100644 index 00000000..9b5ad251 --- /dev/null +++ b/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransactionConstants.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * feature-test-transaction + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.testtransaction; + +import lombok.Getter; + +public class TestTransactionConstants { + + public static final String TT_FPC = "TT.FPC"; + public static final String TT_COUNTER = "$ttc"; + public static final String TT_UUID = "43868e59-d1f3-43c2-bd6f-86f89a61eea5"; + public static final long DEFAULT_TT_TASK_SLEEP = 20000; + + @Getter + private static final TestTransaction manager = new TtImpl(); + + private TestTransactionConstants() { + // do nothing + } +} diff --git a/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransactionFeature.java b/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransactionFeature.java index 3b2c4598..cc8064d4 100644 --- a/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransactionFeature.java +++ b/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TestTransactionFeature.java @@ -83,6 +83,6 @@ public class TestTransactionFeature implements PolicyControllerFeatureApi { * @return the test transaction manager */ protected TestTransaction getTestTransMgr() { - return TestTransaction.manager; + return TestTransactionConstants.getManager(); } } diff --git a/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TtControllerTask.java b/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TtControllerTask.java index cd54eb07..e0296045 100644 --- a/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TtControllerTask.java +++ b/feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TtControllerTask.java @@ -109,7 +109,7 @@ public class TtControllerTask implements Runnable { } if (!getCurrentThread().isInterrupted()) { - doSleep(TestTransaction.DEFAULT_TT_TASK_SLEEP); + doSleep(TestTransactionConstants.DEFAULT_TT_TASK_SLEEP); } } } catch (final InterruptedException e) { @@ -141,7 +141,7 @@ public class TtControllerTask implements Runnable { final List<Object> facts = this.controller .getDrools() - .factQuery(session, TestTransaction.TT_FPC, TestTransaction.TT_COUNTER, false); + .factQuery(session, TestTransactionConstants.TT_FPC, TestTransactionConstants.TT_COUNTER, false); if (facts == null || facts.size() != 1) { /* * unexpected something wrong here, can't expect to recover note this exception is @@ -174,7 +174,7 @@ public class TtControllerTask implements Runnable { fpc); } fpcs.put(session, fpc); - drools.getContainer().insert(session, new EventObject(TestTransaction.TT_UUID)); + drools.getContainer().insert(session, new EventObject(TestTransactionConstants.TT_UUID)); } } diff --git a/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionAdditionalTest.java b/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionAdditionalTest.java index 23fdc215..352779df 100644 --- a/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionAdditionalTest.java +++ b/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionAdditionalTest.java @@ -119,7 +119,7 @@ public class TestTransactionAdditionalTest { @Test public void testTestTransactionImpl() { - assertNotNull(TtImpl.manager); + assertNotNull(TestTransactionConstants.getManager()); } @Test @@ -153,7 +153,7 @@ public class TestTransactionAdditionalTest { // unregister again - stop() should not be called again impl.unregister(controller3); verify(task3).stop(); - + // unregister original controller - no stop() should be called again impl.unregister(controller); verify(task, never()).stop(); diff --git a/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionTest.java b/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionTest.java index e0779ba0..e3c2ed91 100644 --- a/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionTest.java +++ b/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionTest.java @@ -33,10 +33,11 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.BeforeClass; import org.junit.Test; -import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.DroolsProperties; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; +import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.system.PolicyController; -import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.system.PolicyControllerConstants; +import org.onap.policy.drools.system.PolicyEngineConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,7 +56,7 @@ public class TestTransactionTest { /** * Start up. - * + * * @throws IOException exception */ @BeforeClass @@ -65,20 +66,20 @@ public class TestTransactionTest { cleanUpWorkingDir(); /* ensure presence of config directory */ - SystemPersistence.manager.setConfigurationDir(null); + SystemPersistenceConstants.getManager().setConfigurationDir(null); } @Test public void registerUnregisterTest() throws InterruptedException { final Properties controllerProperties = new Properties(); - controllerProperties.put(DroolsProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME); + controllerProperties.put(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME); final PolicyController controller = - PolicyEngine.manager.createPolicyController(TEST_CONTROLLER_NAME, controllerProperties); - assertNotNull(PolicyController.factory.get(TEST_CONTROLLER_NAME)); + PolicyEngineConstants.getManager().createPolicyController(TEST_CONTROLLER_NAME, controllerProperties); + assertNotNull(PolicyControllerConstants.getFactory().get(TEST_CONTROLLER_NAME)); logger.info(controller.toString()); - + CountDownLatch latch = new CountDownLatch(1); - + // use our own impl so we can decrement the latch when run() completes TtImpl impl = new TtImpl() { @Override @@ -90,11 +91,11 @@ public class TestTransactionTest { latch.countDown(); } }; - } + } }; impl.register(controller); - assertNotNull(TestTransaction.manager); + assertNotNull(TestTransactionConstants.getManager()); /* * Unregistering the controller should terminate its TestTransaction thread if it hasn't already @@ -108,7 +109,7 @@ public class TestTransactionTest { /** * Returns thread object based on String name. - * @param latch indicates when the thread has finished running + * @param latch indicates when the thread has finished running * @param threadName thread name * @return the thread * @throws InterruptedException exception @@ -129,8 +130,8 @@ public class TestTransactionTest { /** clean up working directory. */ protected static void cleanUpWorkingDir() { final Path testControllerPath = - Paths.get( - SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE); + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), + TEST_CONTROLLER_FILE); try { Files.deleteIfExists(testControllerPath); } catch (final Exception e) { @@ -138,8 +139,8 @@ public class TestTransactionTest { } final Path testControllerBakPath = - Paths.get( - SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE_BAK); + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), + TEST_CONTROLLER_FILE_BAK); try { Files.deleteIfExists(testControllerBakPath); } catch (final Exception e) { diff --git a/policy-core/pom.xml b/policy-core/pom.xml index a02937ac..6bbfa644 100644 --- a/policy-core/pom.xml +++ b/policy-core/pom.xml @@ -106,6 +106,11 @@ <version>${project.version}</version> </dependency> <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <scope>provided</scope> + </dependency> + <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java index 3b5c360f..584b3845 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java @@ -8,9 +8,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -169,7 +169,7 @@ public class PolicyContainer implements Startable { /** * Get name. - * + * * @return the name of the container, which is the String equivalent of the 'ReleaseId'. It has * the form: * @@ -184,7 +184,7 @@ public class PolicyContainer implements Startable { /** * Get kie container. - * + * * @return the associated 'KieContainer' instance */ public KieContainer getKieContainer() { @@ -193,7 +193,7 @@ public class PolicyContainer implements Startable { /** * Get class loader. - * + * * @return the 'ClassLoader' associated with the 'KieContainer' instance */ public ClassLoader getClassLoader() { @@ -202,7 +202,7 @@ public class PolicyContainer implements Startable { /** * Get group Id. - * + * * @return the Maven GroupId of the top-level artifact wrapped by the container. */ public String getGroupId() { @@ -211,7 +211,7 @@ public class PolicyContainer implements Startable { /** * Get artifact id. - * + * * @return the Maven ArtifactId of the top-level artifact wrapped by the container. */ public String getArtifactId() { @@ -220,7 +220,7 @@ public class PolicyContainer implements Startable { /** * Get version. - * + * * @return the version of the top-level artifact wrapped by the container (this may change as * updates occur) */ @@ -258,7 +258,7 @@ public class PolicyContainer implements Startable { // loop through all of the features, and give each one // a chance to create the 'KieSession' - for (PolicySessionFeatureApi feature : PolicySessionFeatureApi.impl.getList()) { + for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) { try { if ((kieSession = feature.activatePolicySession(this, name, kieBaseName)) != null) { break; @@ -280,7 +280,7 @@ public class PolicyContainer implements Startable { sessions.put(name, session); // notify features - for (PolicySessionFeatureApi feature : PolicySessionFeatureApi.impl.getList()) { + for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) { try { feature.newPolicySession(session); } catch (Exception e) { @@ -289,7 +289,7 @@ public class PolicyContainer implements Startable { } logger.info("activatePolicySession:new session was added in sessions with name {}", name); } - logger.info("activatePolicySession:session - {} is returned.", + logger.info("activatePolicySession:session - {} is returned.", session == null ? "null" : session.getFullName()); return session; } @@ -350,7 +350,7 @@ public class PolicyContainer implements Startable { sessions.put(name, policySession); // notify features - for (PolicySessionFeatureApi feature : PolicySessionFeatureApi.impl.getList()) { + for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) { try { feature.newPolicySession(policySession); } catch (Exception e) { @@ -412,7 +412,7 @@ public class PolicyContainer implements Startable { /** * Get policy containers. - * + * * @return all existing 'PolicyContainer' instances */ public static Collection<PolicyContainer> getPolicyContainers() { @@ -423,14 +423,14 @@ public class PolicyContainer implements Startable { /** * Get policy sessions. - * + * * @return all of the 'PolicySession' instances */ public Collection<PolicySession> getPolicySessions() { // KLUDGE WARNING: this is a temporary workaround -- if there are // no features, we don't have persistence, and 'activate' is never // called. In this case, make sure the container is started. - if (PolicySessionFeatureApi.impl.getList().isEmpty()) { + if (PolicySessionFeatureApiConstants.getImpl().getList().isEmpty()) { start(); } @@ -562,7 +562,7 @@ public class PolicyContainer implements Startable { session.getKieSession().dispose(); // notify features - for (PolicySessionFeatureApi feature : PolicySessionFeatureApi.impl.getList()) { + for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) { try { feature.disposeKieSession(session); } catch (Exception e) { @@ -625,7 +625,7 @@ public class PolicyContainer implements Startable { session.getKieSession().destroy(); // notify features - for (PolicySessionFeatureApi feature : PolicySessionFeatureApi.impl.getList()) { + for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) { try { feature.destroyKieSession(session); } catch (Exception e) { @@ -685,7 +685,7 @@ public class PolicyContainer implements Startable { logger.info("PolicyContainer.main: configDir={}", configDir); // invoke 'globalInit' on all of the features - for (PolicySessionFeatureApi feature : PolicySessionFeatureApi.impl.getList()) { + for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) { try { feature.globalInit(args, configDir); } catch (Exception e) { diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java index f27bb4ab..6352eaa2 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java @@ -143,7 +143,7 @@ public class PolicySession // loop through all of the features, and give each one // a chance to create the 'ThreadModel' for (PolicySessionFeatureApi feature : - PolicySessionFeatureApi.impl.getList()) { + PolicySessionFeatureApiConstants.getImpl().getList()) { try { if ((threadModel = feature.selectThreadModel(this)) != null) { break; diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureApi.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureApi.java index 3d259954..dd9ec154 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureApi.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureApi.java @@ -22,7 +22,6 @@ package org.onap.policy.drools.core; import org.kie.api.runtime.KieSession; import org.onap.policy.common.utils.services.OrderedService; -import org.onap.policy.common.utils.services.OrderedServiceImpl; /** * This interface provides a way to invoke optional features at various @@ -33,12 +32,6 @@ import org.onap.policy.common.utils.services.OrderedServiceImpl; * may */ public interface PolicySessionFeatureApi extends OrderedService { - /** - * 'FeatureAPI.impl.getList()' returns an ordered list of objects - * implementing the 'FeatureAPI' interface. - */ - public static OrderedServiceImpl<PolicySessionFeatureApi> impl = - new OrderedServiceImpl<>(PolicySessionFeatureApi.class); /** * This method is called during initialization at a point right after diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureApiConstants.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureApiConstants.java new file mode 100644 index 00000000..174ac794 --- /dev/null +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureApiConstants.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * policy-core + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.core; + +import lombok.Getter; +import org.onap.policy.common.utils.services.OrderedServiceImpl; + +public class PolicySessionFeatureApiConstants { + /** + * 'FeatureAPI.impl.getList()' returns an ordered list of objects + * implementing the 'FeatureAPI' interface. + */ + @Getter + private static final OrderedServiceImpl<PolicySessionFeatureApi> impl = + new OrderedServiceImpl<>(PolicySessionFeatureApi.class); + + private PolicySessionFeatureApiConstants() { + // do nothing + } +} diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureApi.java b/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureApi.java index ff7de049..b7968486 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureApi.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureApi.java @@ -21,7 +21,6 @@ package org.onap.policy.drools.core.lock; import org.onap.policy.common.utils.services.OrderedService; -import org.onap.policy.common.utils.services.OrderedServiceImpl; /** * Resource locks. Each lock has an "owner", which is intended to be unique across a @@ -38,13 +37,6 @@ import org.onap.policy.common.utils.services.OrderedServiceImpl; public interface PolicyResourceLockFeatureApi extends OrderedService { /** - * 'FeatureAPI.impl.getList()' returns an ordered list of objects implementing the - * 'FeatureAPI' interface. - */ - public static OrderedServiceImpl<PolicyResourceLockFeatureApi> impl = - new OrderedServiceImpl<>(PolicyResourceLockFeatureApi.class); - - /** * Result of a requested operation. */ public enum OperResult { diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureApiConstants.java b/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureApiConstants.java new file mode 100644 index 00000000..8510e3d9 --- /dev/null +++ b/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureApiConstants.java @@ -0,0 +1,39 @@ +/* + * ============LICENSE_START======================================================= + * api-resource-locks + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.core.lock; + +import lombok.Getter; +import org.onap.policy.common.utils.services.OrderedServiceImpl; + +public class PolicyResourceLockFeatureApiConstants { + + /** + * 'FeatureAPI.impl.getList()' returns an ordered list of objects implementing the + * 'FeatureAPI' interface. + */ + @Getter + private static final OrderedServiceImpl<PolicyResourceLockFeatureApi> impl = + new OrderedServiceImpl<>(PolicyResourceLockFeatureApi.class); + + private PolicyResourceLockFeatureApiConstants() { + // do nothing + } +} diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockManager.java b/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockManager.java index 487814cb..0e73eac1 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockManager.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockManager.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -43,7 +43,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { /** * Get instance. - * + * * @return the manager singleton */ public static PolicyResourceLockManager getInstance() { @@ -118,7 +118,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { /** * Is locked. - * + * * @throws IllegalArgumentException if the resourceId is {@code null} */ @Override @@ -128,7 +128,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { } - return doBoolIntercept(impl -> impl.beforeIsLocked(resourceId), () -> + return doBoolIntercept(impl -> impl.beforeIsLocked(resourceId), () -> // implementer didn't do the work - defer to the superclass super.isLocked(resourceId) @@ -137,7 +137,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { /** * Is locked by. - * + * * @throws IllegalArgumentException if the resourceId or owner is {@code null} */ @Override @@ -150,7 +150,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { throw makeNullArgException(MSG_NULL_OWNER); } - return doBoolIntercept(impl -> impl.beforeIsLockedBy(resourceId, owner), () -> + return doBoolIntercept(impl -> impl.beforeIsLockedBy(resourceId, owner), () -> // implementer didn't do the work - defer to the superclass super.isLockedBy(resourceId, owner) @@ -161,7 +161,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { * Applies a function to each implementer of the lock feature. Returns as soon as one * of them returns a result other than <b>OPER_UNHANDLED</b>. If they all return * <b>OPER_UNHANDLED</b>, then it returns the result of applying the default function. - * + * * @param interceptFunc intercept function * @param defaultFunc default function * @return {@code true} if success, {@code false} otherwise @@ -180,7 +180,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { /** * Applies a function to each implementer of the lock feature. Returns as soon as one * of them returns a non-null value. - * + * * @param continueValue if the implementer returns this value, then it continues to * check addition implementers * @param func function to be applied to the implementers @@ -208,11 +208,11 @@ public class PolicyResourceLockManager extends SimpleLockManager { /** * Get implementers. - * + * * @return the list of feature implementers */ protected List<PolicyResourceLockFeatureApi> getImplementers() { - return PolicyResourceLockFeatureApi.impl.getList(); + return PolicyResourceLockFeatureApiConstants.getImpl().getList(); } /** @@ -221,7 +221,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { private static class Singleton { private static final PolicyResourceLockManager instance = new PolicyResourceLockManager(); - + /** * Not invoked. */ diff --git a/policy-core/src/main/java/org/onap/policy/drools/properties/DroolsProperties.java b/policy-core/src/main/java/org/onap/policy/drools/properties/DroolsPropertyConstants.java index 0b7a6503..f14486bc 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/properties/DroolsProperties.java +++ b/policy-core/src/main/java/org/onap/policy/drools/properties/DroolsPropertyConstants.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * policy-core * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,18 +20,22 @@ package org.onap.policy.drools.properties; -public interface DroolsProperties { +public class DroolsPropertyConstants { /* Controller Properties */ - String PROPERTY_CONTROLLER_NAME = "controller.name"; + public static final String PROPERTY_CONTROLLER_NAME = "controller.name"; - String DEFAULT_CONTROLLER_POLICY_TYPE_VERSION = "1.0.0"; - String PROPERTY_CONTROLLER_POLICY_TYPES = "controller.policy.types"; + public static final String DEFAULT_CONTROLLER_POLICY_TYPE_VERSION = "1.0.0"; + public static final String PROPERTY_CONTROLLER_POLICY_TYPES = "controller.policy.types"; /* Drools Properties */ - String RULES_GROUPID = "rules.groupId"; - String RULES_ARTIFACTID = "rules.artifactId"; - String RULES_VERSION = "rules.version"; + public static final String RULES_GROUPID = "rules.groupId"; + public static final String RULES_ARTIFACTID = "rules.artifactId"; + public static final String RULES_VERSION = "rules.version"; + + private DroolsPropertyConstants() { + // do nothing + } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsController.java b/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsController.java index 4347614f..dd654b1d 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsController.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -35,56 +35,36 @@ import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration; public interface DroolsController extends Startable, Lockable { /** - * No Group ID identifier. - */ - String NO_GROUP_ID = "NO-GROUP-ID"; - - /** - * No Artifact ID identifier. - */ - String NO_ARTIFACT_ID = "NO-ARTIFACT-ID"; - - /** - * No version identifier. - */ - String NO_VERSION = "NO-VERSION"; - - /** - * Factory to track and manage drools controllers. - */ - DroolsControllerFactory factory = new IndexedDroolsControllerFactory(); - - /** * get group id. - * + * * @return group id */ String getGroupId(); /** * get artifact id. - * + * * @return artifact id */ String getArtifactId(); /** * get version. - * + * * @return version */ String getVersion(); /** * return the policy session names. - * + * * @return policy session */ List<String> getSessionNames(); /** * return the policy full session names. - * + * * @return policy session */ List<String> getCanonicalSessionNames(); @@ -98,10 +78,10 @@ public interface DroolsController extends Startable, Lockable { /** * offers a raw event to this controller for processing. - * + * * @param topic topic associated with the event * @param event the event - * + * * @return true if the operation was successful */ boolean offer(String topic, String event); @@ -117,7 +97,7 @@ public interface DroolsController extends Startable, Lockable { /** * delivers "event" to "sink". - * + * * @param sink destination * @param event event * @return true if successful, false if a failure has occurred. @@ -131,28 +111,28 @@ public interface DroolsController extends Startable, Lockable { /** * Get recent source events. - * + * * @return the most recent received events. */ Object[] getRecentSourceEvents(); /** * Get recent sink events. - * + * * @return the most recent delivered events */ String[] getRecentSinkEvents(); /** * Get container. - * + * * @return the underlying policy container */ PolicyContainer getContainer(); /** * Does it owns the coder. - * + * * @param coderClass the encoder object * @param modelHash the hash for the model * @return true it owns it @@ -161,7 +141,7 @@ public interface DroolsController extends Startable, Lockable { /** * fetches a class from the model. - * + * * @param className the class to fetch * @return the actual class object, or null if not found */ @@ -174,13 +154,13 @@ public interface DroolsController extends Startable, Lockable { /** * update the new version of the maven jar rules file. - * + * * @param newGroupId - new group id * @param newArtifactId - new artifact id * @param newVersion - new version * @param decoderConfigurations - decoder configurations * @param encoderConfigurations - encoder configurations - * + * * @throws Exception from within drools libraries * @throws LinkageError from within drools libraries */ @@ -190,7 +170,7 @@ public interface DroolsController extends Startable, Lockable { /** * gets the classnames of facts as well as the current count. - * + * * @param sessionName the session name * @return map of class to count */ @@ -198,7 +178,7 @@ public interface DroolsController extends Startable, Lockable { /** * gets the count of facts for a given session. - * + * * @param sessionName the session name * @return the fact count */ @@ -206,7 +186,7 @@ public interface DroolsController extends Startable, Lockable { /** * gets all the facts of a given class for a given session. - * + * * @param sessionName the session identifier * @param className the class type * @param delete retract from drools the results of the query? @@ -221,7 +201,7 @@ public interface DroolsController extends Startable, Lockable { /** * gets the facts associated with a query for a give session for a given queried entity. - * + * * @param sessionName the session * @param queryName the query identifier * @param queriedEntity the queried entity @@ -254,7 +234,7 @@ public interface DroolsController extends Startable, Lockable { /** * halts and permanently releases all resources. - * + * */ void halt(); } diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsControllerConstants.java b/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsControllerConstants.java new file mode 100644 index 00000000..16cf3592 --- /dev/null +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsControllerConstants.java @@ -0,0 +1,51 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.controller; + +import lombok.Getter; + +public class DroolsControllerConstants { + + /** + * No Group ID identifier. + */ + public static final String NO_GROUP_ID = "NO-GROUP-ID"; + + /** + * No Artifact ID identifier. + */ + public static final String NO_ARTIFACT_ID = "NO-ARTIFACT-ID"; + + /** + * No version identifier. + */ + public static final String NO_VERSION = "NO-VERSION"; + + /** + * Factory to track and manage drools controllers. + */ + @Getter + private static final DroolsControllerFactory factory = new IndexedDroolsControllerFactory(); + + private DroolsControllerConstants() { + // do nothing + } +} diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/IndexedDroolsControllerFactory.java b/policy-management/src/main/java/org/onap/policy/drools/controller/IndexedDroolsControllerFactory.java index 89e2a1a8..733a492d 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/IndexedDroolsControllerFactory.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/IndexedDroolsControllerFactory.java @@ -32,7 +32,7 @@ import org.onap.policy.common.endpoints.event.comm.TopicSource; import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.drools.controller.internal.MavenDroolsController; import org.onap.policy.drools.controller.internal.NullDroolsController; -import org.onap.policy.drools.properties.DroolsProperties; +import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder; @@ -79,19 +79,19 @@ class IndexedDroolsControllerFactory implements DroolsControllerFactory { public DroolsController build(Properties properties, List<? extends TopicSource> eventSources, List<? extends TopicSink> eventSinks) throws LinkageError { - String groupId = properties.getProperty(DroolsProperties.RULES_GROUPID); + String groupId = properties.getProperty(DroolsPropertyConstants.RULES_GROUPID); if (groupId == null || groupId.isEmpty()) { - groupId = DroolsController.NO_GROUP_ID; + groupId = DroolsControllerConstants.NO_GROUP_ID; } - String artifactId = properties.getProperty(DroolsProperties.RULES_ARTIFACTID); + String artifactId = properties.getProperty(DroolsPropertyConstants.RULES_ARTIFACTID); if (artifactId == null || artifactId.isEmpty()) { - artifactId = DroolsController.NO_ARTIFACT_ID; + artifactId = DroolsControllerConstants.NO_ARTIFACT_ID; } - String version = properties.getProperty(DroolsProperties.RULES_VERSION); + String version = properties.getProperty(DroolsPropertyConstants.RULES_VERSION); if (version == null || version.isEmpty()) { - version = DroolsController.NO_VERSION; + version = DroolsControllerConstants.NO_VERSION; } List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = codersAndFilters(properties, eventSources); diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java index b09ae85c..ca1f2283 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java @@ -43,11 +43,14 @@ import org.onap.policy.common.gson.annotation.GsonJsonIgnore; import org.onap.policy.common.gson.annotation.GsonJsonProperty; import org.onap.policy.common.utils.services.OrderedServiceImpl; import org.onap.policy.drools.controller.DroolsController; +import org.onap.policy.drools.controller.DroolsControllerConstants; import org.onap.policy.drools.core.PolicyContainer; import org.onap.policy.drools.core.PolicySession; import org.onap.policy.drools.core.jmx.PdpJmx; import org.onap.policy.drools.features.DroolsControllerFeatureApi; +import org.onap.policy.drools.features.DroolsControllerFeatureApiConstants; import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants; import org.onap.policy.drools.protocol.coders.EventProtocolParams; import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration; @@ -64,6 +67,8 @@ import org.slf4j.LoggerFactory; */ public class MavenDroolsController implements DroolsController { + private static final String FACT_RETRIEVE_ERROR = "Object cannot be retrieved from fact {}"; + /** * logger. */ @@ -193,9 +198,9 @@ public class MavenDroolsController implements DroolsController { throw new IllegalArgumentException("Missing maven version coordinate"); } - if (newGroupId.equalsIgnoreCase(DroolsController.NO_GROUP_ID) - || newArtifactId.equalsIgnoreCase(DroolsController.NO_ARTIFACT_ID) - || newVersion.equalsIgnoreCase(DroolsController.NO_VERSION)) { + if (newGroupId.equalsIgnoreCase(DroolsControllerConstants.NO_GROUP_ID) + || newArtifactId.equalsIgnoreCase(DroolsControllerConstants.NO_ARTIFACT_ID) + || newVersion.equalsIgnoreCase(DroolsControllerConstants.NO_VERSION)) { throw new IllegalArgumentException("BRAINLESS maven coordinates provided: " + newGroupId + ":" + newArtifactId + ":" + newVersion); @@ -755,7 +760,7 @@ public class MavenDroolsController implements DroolsController { classNames.put(className, 1); } } catch (Exception e) { - logger.warn("Object cannot be retrieved from fact {}", fact, e); + logger.warn(FACT_RETRIEVE_ERROR, fact, e); } } @@ -803,7 +808,7 @@ public class MavenDroolsController implements DroolsController { kieSession.delete(factHandle); } } catch (Exception e) { - logger.warn("Object cannot be retrieved from fact {}", factHandle, e); + logger.warn(FACT_RETRIEVE_ERROR, factHandle, e); } } @@ -881,7 +886,7 @@ public class MavenDroolsController implements DroolsController { return true; } } catch (Exception e) { - logger.warn("Object cannot be retrieved from fact {}", factHandle, e); + logger.warn(FACT_RETRIEVE_ERROR, factHandle, e); } } return false; @@ -889,7 +894,7 @@ public class MavenDroolsController implements DroolsController { @Override public <T> boolean delete(@NonNull T fact) { - return this.getSessionNames().stream().map((ss) -> delete(ss, fact)).reduce(false, Boolean::logicalOr); + return this.getSessionNames().stream().map(ss -> delete(ss, fact)).reduce(false, Boolean::logicalOr); } @Override @@ -903,7 +908,7 @@ public class MavenDroolsController implements DroolsController { try { kieSession.delete(factHandle); } catch (Exception e) { - logger.warn("Object cannot be retrieved from fact {}", factHandle, e); + logger.warn(FACT_RETRIEVE_ERROR, factHandle, e); success = false; } } @@ -912,7 +917,7 @@ public class MavenDroolsController implements DroolsController { @Override public <T> boolean delete(@NonNull Class<T> fact) { - return this.getSessionNames().stream().map((ss) -> delete(ss, fact)).reduce(false, Boolean::logicalOr); + return this.getSessionNames().stream().map(ss -> delete(ss, fact)).reduce(false, Boolean::logicalOr); } @@ -972,11 +977,11 @@ public class MavenDroolsController implements DroolsController { // these may be overridden by junit tests protected EventProtocolCoder getCoderManager() { - return EventProtocolCoder.manager; + return EventProtocolCoderConstants.getManager(); } protected OrderedServiceImpl<DroolsControllerFeatureApi> getDroolsProviders() { - return DroolsControllerFeatureApi.providers; + return DroolsControllerFeatureApiConstants.getProviders(); } protected PolicyContainer makePolicyContainer(String groupId, String artifactId, String version) { diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java index 4b38e722..5416d321 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,6 +28,7 @@ import java.util.Map; import org.checkerframework.checker.nullness.qual.NonNull; import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.drools.controller.DroolsController; +import org.onap.policy.drools.controller.DroolsControllerConstants; import org.onap.policy.drools.core.PolicyContainer; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration; @@ -78,17 +79,17 @@ public class NullDroolsController implements DroolsController { @Override public String getGroupId() { - return NO_GROUP_ID; + return DroolsControllerConstants.NO_GROUP_ID; } @Override public String getArtifactId() { - return NO_ARTIFACT_ID; + return DroolsControllerConstants.NO_ARTIFACT_ID; } @Override public String getVersion() { - return NO_VERSION; + return DroolsControllerConstants.NO_VERSION; } @Override @@ -187,8 +188,8 @@ public class NullDroolsController implements DroolsController { } @Override - public List<Object> factQuery(String sessionName, String queryName, - String queriedEntity, + public List<Object> factQuery(String sessionName, String queryName, + String queriedEntity, boolean delete, Object... queryParams) { return new ArrayList<>(); } diff --git a/policy-management/src/main/java/org/onap/policy/drools/features/DroolsControllerFeatureApi.java b/policy-management/src/main/java/org/onap/policy/drools/features/DroolsControllerFeatureApi.java index d5a16a12..abf524e4 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/features/DroolsControllerFeatureApi.java +++ b/policy-management/src/main/java/org/onap/policy/drools/features/DroolsControllerFeatureApi.java @@ -22,7 +22,6 @@ package org.onap.policy.drools.features; import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.common.utils.services.OrderedService; -import org.onap.policy.common.utils.services.OrderedServiceImpl; import org.onap.policy.drools.controller.DroolsController; /** @@ -74,10 +73,4 @@ public interface DroolsControllerFeatureApi extends OrderedService { boolean success) { return false; } - - /** - * Feature providers implementing this interface. - */ - public static final OrderedServiceImpl<DroolsControllerFeatureApi> providers = - new OrderedServiceImpl<>(DroolsControllerFeatureApi.class); } diff --git a/policy-management/src/main/java/org/onap/policy/drools/features/DroolsControllerFeatureApiConstants.java b/policy-management/src/main/java/org/onap/policy/drools/features/DroolsControllerFeatureApiConstants.java new file mode 100644 index 00000000..5ff8e86f --- /dev/null +++ b/policy-management/src/main/java/org/onap/policy/drools/features/DroolsControllerFeatureApiConstants.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.features; + +import lombok.Getter; +import org.onap.policy.common.utils.services.OrderedServiceImpl; + +public class DroolsControllerFeatureApiConstants { + + /** + * Feature providers implementing this interface. + */ + @Getter + private static final OrderedServiceImpl<DroolsControllerFeatureApi> providers = + new OrderedServiceImpl<>(DroolsControllerFeatureApi.class); + + private DroolsControllerFeatureApiConstants() { + // do nothing + } +} diff --git a/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureApi.java b/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureApi.java index c9e78c6a..9c6ac223 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureApi.java +++ b/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureApi.java @@ -23,18 +23,11 @@ package org.onap.policy.drools.features; import java.util.Properties; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.common.utils.services.OrderedService; -import org.onap.policy.common.utils.services.OrderedServiceImpl; import org.onap.policy.drools.system.PolicyController; public interface PolicyControllerFeatureApi extends OrderedService { /** - * Feature providers implementing this interface. - */ - OrderedServiceImpl<PolicyControllerFeatureApi> providers = - new OrderedServiceImpl<>(PolicyControllerFeatureApi.class); - - /** * called before creating a controller with name 'name' and * properties 'properties'. * diff --git a/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureApiConstants.java b/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureApiConstants.java new file mode 100644 index 00000000..230228f0 --- /dev/null +++ b/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureApiConstants.java @@ -0,0 +1,38 @@ +/* + * ============LICENSE_START======================================================= + * policy-management + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.features; + +import lombok.Getter; +import org.onap.policy.common.utils.services.OrderedServiceImpl; + +public class PolicyControllerFeatureApiConstants { + + /** + * Feature providers implementing this interface. + */ + @Getter + private static final OrderedServiceImpl<PolicyControllerFeatureApi> providers = + new OrderedServiceImpl<>(PolicyControllerFeatureApi.class); + + private PolicyControllerFeatureApiConstants() { + // do nothing + } +} diff --git a/policy-management/src/main/java/org/onap/policy/drools/features/PolicyEngineFeatureApi.java b/policy-management/src/main/java/org/onap/policy/drools/features/PolicyEngineFeatureApi.java index bd834c4d..b6d827a4 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/features/PolicyEngineFeatureApi.java +++ b/policy-management/src/main/java/org/onap/policy/drools/features/PolicyEngineFeatureApi.java @@ -23,7 +23,6 @@ package org.onap.policy.drools.features; import java.util.Properties; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.common.utils.services.OrderedService; -import org.onap.policy.common.utils.services.OrderedServiceImpl; import org.onap.policy.drools.protocol.configuration.PdpdConfiguration; import org.onap.policy.drools.system.PolicyEngine; @@ -32,11 +31,6 @@ import org.onap.policy.drools.system.PolicyEngine; * Provides Interception Points during the Policy Engine lifecycle. */ public interface PolicyEngineFeatureApi extends OrderedService { - /** - * Feature providers implementing this interface. - */ - public static final OrderedServiceImpl<PolicyEngineFeatureApi> providers = - new OrderedServiceImpl<>(PolicyEngineFeatureApi.class); /** * intercept before the Policy Engine is commanded to boot. diff --git a/policy-management/src/main/java/org/onap/policy/drools/features/PolicyEngineFeatureApiConstants.java b/policy-management/src/main/java/org/onap/policy/drools/features/PolicyEngineFeatureApiConstants.java new file mode 100644 index 00000000..e62714a5 --- /dev/null +++ b/policy-management/src/main/java/org/onap/policy/drools/features/PolicyEngineFeatureApiConstants.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * policy-engine + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.features; + +import lombok.Getter; +import org.onap.policy.common.utils.services.OrderedServiceImpl; + +public class PolicyEngineFeatureApiConstants { + /** + * Feature providers implementing this interface. + */ + @Getter + private static final OrderedServiceImpl<PolicyEngineFeatureApi> providers = + new OrderedServiceImpl<>(PolicyEngineFeatureApi.class); + + private PolicyEngineFeatureApiConstants() { + // do nothing + } +} diff --git a/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java b/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java index 88987eab..ca1ad371 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java +++ b/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java @@ -34,7 +34,7 @@ import java.util.List; import java.util.Properties; import java.util.function.BiPredicate; -import org.onap.policy.drools.properties.DroolsProperties; +import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.utils.PropertyUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -111,7 +111,7 @@ public class FileSystemPersistence implements SystemPersistence { /** * Configuration directory. */ - protected Path configurationDirectory = Paths.get(DEFAULT_CONFIGURATION_DIR); + protected Path configurationDirectory = Paths.get(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR); /** * Logger. @@ -123,11 +123,11 @@ public class FileSystemPersistence implements SystemPersistence { String tempConfigDir = configDir; if (tempConfigDir == null) { - tempConfigDir = DEFAULT_CONFIGURATION_DIR; - this.configurationDirectory = Paths.get(DEFAULT_CONFIGURATION_DIR); + tempConfigDir = SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR; + this.configurationDirectory = Paths.get(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR); } - if (!tempConfigDir.equals(DEFAULT_CONFIGURATION_DIR)) { + if (!tempConfigDir.equals(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR)) { this.configurationDirectory = Paths.get(tempConfigDir); } @@ -263,9 +263,9 @@ public class FileSystemPersistence implements SystemPersistence { private boolean testControllerName(String controllerFilename, Properties controllerProperties) { String controllerName = controllerFilename .substring(0, controllerFilename.length() - PROPERTIES_FILE_CONTROLLER_SUFFIX.length()); - String controllerPropName = controllerProperties.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME); + String controllerPropName = controllerProperties.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME); if (controllerPropName == null) { - controllerProperties.setProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME, controllerName); + controllerProperties.setProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, controllerName); } else if (!controllerPropName.equals(controllerName)) { logger.error("{}: mismatch controller named {} against {} in file {}", this, controllerPropName, controllerName, controllerFilename); @@ -290,7 +290,7 @@ public class FileSystemPersistence implements SystemPersistence { if (Files.exists(path)) { try { logger.info("{}: there is an existing configuration file @ {} ", this, path); - Path bakPath = Paths.get(this.configurationDirectory.toString(), + Path bakPath = Paths.get(this.configurationDirectory.toString(), name + fileSuffix + FILE_BACKUP_SUFFIX); Files.copy(path, bakPath, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { @@ -365,7 +365,7 @@ public class FileSystemPersistence implements SystemPersistence { if (Files.exists(path)) { try { - Path bakPath = Paths.get(this.configurationDirectory.toString(), + Path bakPath = Paths.get(this.configurationDirectory.toString(), name + fileSuffix + FILE_BACKUP_SUFFIX); Files.move(path, bakPath, StandardCopyOption.REPLACE_EXISTING); } catch (final Exception e) { diff --git a/policy-management/src/main/java/org/onap/policy/drools/persistence/SystemPersistence.java b/policy-management/src/main/java/org/onap/policy/drools/persistence/SystemPersistence.java index ee1e8b52..d5a35c32 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/persistence/SystemPersistence.java +++ b/policy-management/src/main/java/org/onap/policy/drools/persistence/SystemPersistence.java @@ -28,16 +28,6 @@ import java.util.Properties; * System Configuration. */ public interface SystemPersistence { - /** - * configuration directory. - */ - String DEFAULT_CONFIGURATION_DIR = "config"; - - /** - * Persistence Manager. For now it is a file-based properties management, In the future, it will - * probably be DB based, so manager implementation will change. - */ - SystemPersistence manager = new FileSystemPersistence(); /** * sets a configuration directory and ensures it exists. diff --git a/policy-management/src/main/java/org/onap/policy/drools/persistence/SystemPersistenceConstants.java b/policy-management/src/main/java/org/onap/policy/drools/persistence/SystemPersistenceConstants.java new file mode 100644 index 00000000..0b46fb02 --- /dev/null +++ b/policy-management/src/main/java/org/onap/policy/drools/persistence/SystemPersistenceConstants.java @@ -0,0 +1,41 @@ +/* + * ============LICENSE_START======================================================= + * policy-management + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.persistence; + +import lombok.Getter; + +public class SystemPersistenceConstants { + /** + * configuration directory. + */ + public static final String DEFAULT_CONFIGURATION_DIR = "config"; + + /** + * Persistence Manager. For now it is a file-based properties management, In the future, it will + * probably be DB based, so manager implementation will change. + */ + @Getter + private static final SystemPersistence manager = new FileSystemPersistence(); + + private SystemPersistenceConstants() { + // do nothing + } +} diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoder.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoder.java index 62a0cbe2..6cbe94ae 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoder.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoder.java @@ -29,11 +29,6 @@ import org.onap.policy.drools.controller.DroolsController; */ public interface EventProtocolCoder { - /** - * singleton reference to the global event protocol coder. - */ - public static EventProtocolCoder manager = new MultiplexorEventProtocolCoder(); - public static class CoderFilters { /** diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderConstants.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderConstants.java new file mode 100644 index 00000000..45dc39e4 --- /dev/null +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderConstants.java @@ -0,0 +1,37 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright(C) 2018 Samsung Electronics Co., Ltd. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.protocol.coders; + +import lombok.Getter; + +public class EventProtocolCoderConstants { + + /** + * singleton reference to the global event protocol coder. + */ + @Getter + private static final EventProtocolCoder manager = new MultiplexorEventProtocolCoder(); + + private EventProtocolCoderConstants() { + // do nothing + } +} diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GenericEventProtocolCoder.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GenericEventProtocolCoder.java index 8643da3d..89a7a420 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GenericEventProtocolCoder.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GenericEventProtocolCoder.java @@ -26,6 +26,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import org.onap.policy.drools.controller.DroolsController; +import org.onap.policy.drools.controller.DroolsControllerConstants; import org.onap.policy.drools.protocol.coders.EventProtocolCoder.CoderFilters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,15 +36,11 @@ import org.slf4j.LoggerFactory; * parsing tools. */ abstract class GenericEventProtocolCoder { - private static final String INVALID_ARTIFACT_ID_MSG = "Invalid artifact id"; - private static final String INVALID_GROUP_ID_MSG = "Invalid group id"; - private static final String INVALID_TOPIC_MSG = "Invalid Topic"; - private static final String UNSUPPORTED_MSG = "Unsupported"; - + private static final String UNSUPPORTED_EX_MSG = "Unsupported:"; private static final String MISSING_CLASS = "class must be provided"; private static Logger logger = LoggerFactory.getLogger(GenericEventProtocolCoder.class); @@ -287,7 +284,7 @@ abstract class GenericEventProtocolCoder { if (!isCodingSupported(groupId, artifactId, topic)) { throw new IllegalArgumentException( - "Unsupported:" + codersKey(groupId, artifactId, topic) + " for encoding"); + UNSUPPORTED_EX_MSG + codersKey(groupId, artifactId, topic) + " for encoding"); } String key = this.codersKey(groupId, artifactId, topic); @@ -318,7 +315,7 @@ abstract class GenericEventProtocolCoder { public String encode(String groupId, String artifactId, String topic, Object event) { if (!isCodingSupported(groupId, artifactId, topic)) { - throw new IllegalArgumentException("Unsupported:" + codersKey(groupId, artifactId, topic)); + throw new IllegalArgumentException(UNSUPPORTED_EX_MSG + codersKey(groupId, artifactId, topic)); } if (event == null) { @@ -455,7 +452,8 @@ abstract class GenericEventProtocolCoder { List<CoderFilters> coderFilters = encoderSet.getCoders(); for (CoderFilters coder : coderFilters) { if (coder.getCodedClass().equals(encodedClass.getClass().getName())) { - DroolsController droolsController = DroolsController.factory.get(groupId, artifactId, ""); + DroolsController droolsController = + DroolsControllerConstants.getFactory().get(groupId, artifactId, ""); if (droolsController.ownsCoder( encodedClass.getClass(), coder.getModelClassLoaderHash())) { droolsControllers.add(droolsController); @@ -487,7 +485,7 @@ abstract class GenericEventProtocolCoder { public List<CoderFilters> getFilters(String groupId, String artifactId, String topic) { if (!isCodingSupported(groupId, artifactId, topic)) { - throw new IllegalArgumentException("Unsupported:" + codersKey(groupId, artifactId, topic)); + throw new IllegalArgumentException(UNSUPPORTED_EX_MSG + codersKey(groupId, artifactId, topic)); } String key = this.codersKey(groupId, artifactId, topic); @@ -540,7 +538,7 @@ abstract class GenericEventProtocolCoder { String groupId, String artifactId, String topic, String classname) { if (!isCodingSupported(groupId, artifactId, topic)) { - throw new IllegalArgumentException("Unsupported:" + codersKey(groupId, artifactId, topic)); + throw new IllegalArgumentException(UNSUPPORTED_EX_MSG + codersKey(groupId, artifactId, topic)); } if (classname == null || classname.isEmpty()) { @@ -565,7 +563,7 @@ abstract class GenericEventProtocolCoder { String groupId, String artifactId, String topic) { if (!isCodingSupported(groupId, artifactId, topic)) { - throw new IllegalArgumentException("Unsupported:" + codersKey(groupId, artifactId, topic)); + throw new IllegalArgumentException(UNSUPPORTED_EX_MSG + codersKey(groupId, artifactId, topic)); } String key = this.codersKey(groupId, artifactId, topic); diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GsonProtocolCoderToolset.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GsonProtocolCoderToolset.java index 57976a3e..ff154fb5 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GsonProtocolCoderToolset.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GsonProtocolCoderToolset.java @@ -37,6 +37,7 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import org.onap.policy.common.gson.annotation.GsonJsonIgnore; import org.onap.policy.drools.controller.DroolsController; +import org.onap.policy.drools.controller.DroolsControllerConstants; import org.onap.policy.drools.protocol.coders.EventProtocolCoder.CoderFilters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,6 +46,8 @@ import org.slf4j.LoggerFactory; * Tools used for encoding/decoding using GSON. */ class GsonProtocolCoderToolset extends ProtocolCoderToolset { + private static final String FETCH_CLASS_EX_MSG = "cannot fetch application class "; + /** * Logger. */ @@ -155,7 +158,7 @@ class GsonProtocolCoderToolset extends ProtocolCoderToolset { public Object decode(String json) { final DroolsController droolsController = - DroolsController.factory.get(this.groupId, this.artifactId, ""); + DroolsControllerConstants.getFactory().get(this.groupId, this.artifactId, ""); if (droolsController == null) { logger.warn("{}: no drools-controller to process {}", this, json); throw new IllegalStateException("no drools-controller to process event"); @@ -173,13 +176,13 @@ class GsonProtocolCoderToolset extends ProtocolCoderToolset { if (decoderClass == null) { logger.warn("{}: cannot fetch application class {}", this, decoderFilter.getCodedClass()); throw new IllegalStateException( - "cannot fetch application class " + decoderFilter.getCodedClass()); + FETCH_CLASS_EX_MSG + decoderFilter.getCodedClass()); } } catch (final Exception e) { logger.warn("{}: cannot fetch application class {} because of {}", this, decoderFilter.getCodedClass(), e.getMessage()); throw new UnsupportedOperationException( - "cannot fetch application class " + decoderFilter.getCodedClass(), e); + FETCH_CLASS_EX_MSG + decoderFilter.getCodedClass(), e); } if (this.customCoder != null) { @@ -195,7 +198,7 @@ class GsonProtocolCoderToolset extends ProtocolCoderToolset { logger.warn("{}: cannot fetch application class {} because of {}", this, decoderFilter.getCodedClass(), e.getMessage()); throw new UnsupportedOperationException( - "cannot fetch application class " + decoderFilter.getCodedClass(), e); + FETCH_CLASS_EX_MSG + decoderFilter.getCodedClass(), e); } } else { try { @@ -218,7 +221,7 @@ class GsonProtocolCoderToolset extends ProtocolCoderToolset { if (this.customCoder != null) { try { final DroolsController droolsController = - DroolsController.factory.get(this.groupId, this.artifactId, null); + DroolsControllerConstants.getFactory().get(this.groupId, this.artifactId, null); final Class<?> gsonClassContainer = droolsController.fetchModelClass(this.customCoder.getClassContainer()); final Field gsonField = gsonClassContainer.getField(this.customCoder.staticCoderField); diff --git a/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java b/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java index a5fbfdd3..2d40a1f1 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java +++ b/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java @@ -58,15 +58,17 @@ import org.onap.policy.common.endpoints.event.comm.TopicSource; import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.features.PolicyControllerFeatureApi; import org.onap.policy.drools.features.PolicyEngineFeatureApi; -import org.onap.policy.drools.properties.DroolsProperties; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.protocol.coders.EventProtocolCoder.CoderFilters; +import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants; import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; import org.onap.policy.drools.protocol.coders.ProtocolCoderToolset; import org.onap.policy.drools.protocol.configuration.ControllerConfiguration; import org.onap.policy.drools.protocol.configuration.PdpdConfiguration; import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyControllerConstants; import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.system.PolicyEngineConstants; import org.onap.policy.drools.utils.logging.LoggerUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -84,10 +86,49 @@ import org.slf4j.LoggerFactory; schemes = {SwaggerDefinition.Scheme.HTTP}, tags = {@Tag(name = "pdp-d-telemetry", description = "Drools PDP Telemetry Operations")}) public class RestManager { + + private static final String CANNOT_PERFORM_OPERATION = "cannot perform operation"; + private static final String NO_FILTERS = " no filters"; + private static final String NOT_FOUND = " not found: "; + private static final String NOT_FOUND_MSG = " not found"; + private static final String DOES_NOT_EXIST_MSG = " does not exist"; + private static final String NOT_ACCEPTABLE_MSG = " not acceptable"; + private static final String FETCH_POLICY_FAILED = "{}: cannot get policy-controller because of {}"; + private static final String FETCH_POLICY_BY_NAME_FAILED = "{}: cannot get policy-controller {} because of {}"; + private static final String FETCH_POLICY_BY_TOPIC_FAILED = + "{}: cannot get policy-controller {} topic {} because of {}"; + private static final String FETCH_DROOLS_FAILED = "{}: cannot get drools-controller {} because of {}"; + private static final String FETCH_DROOLS_BY_ENTITY_FAILED = + "{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}"; + private static final String FETCH_DROOLS_BY_PARAMS_FAILED = + "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}"; + private static final String FETCH_DROOLS_BY_FACTTYPE_FAILED = + "{}: cannot get: drools-controller {}, session {}, factType {}, because of {}"; + private static final String FETCH_DECODERS_BY_POLICY_FAILED = + "{}: cannot get decoders for policy-controller {} because of {}"; + private static final String FETCH_DECODERS_BY_TOPIC_FAILED = + "{}: cannot get decoders for policy-controller {} topic {} because of {}"; + private static final String FETCH_DECODER_BY_TYPE_FAILED = + "{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}"; + private static final String FETCH_DECODER_BY_FILTER_FAILED = + "{}: cannot get decoder filters for policy-controller {} topic {} type {} filters {} because of {}"; + private static final String FETCH_ENCODER_BY_FILTER_FAILED = + "{}: cannot get encoder filters for policy-controller {} because of {}"; + /** * Logger. */ - private static Logger logger = LoggerFactory.getLogger(RestManager.class); + private static final Logger logger = LoggerFactory.getLogger(RestManager.class); + + /** + * Feed Ports into Resources. + */ + private static final List<String> INPUTS = Arrays.asList("configuration"); + + /** + * Resource Toggles. + */ + private static final List<String> SWITCHES = Arrays.asList("activation", "lock"); /** * GET. @@ -99,7 +140,7 @@ public class RestManager { @ApiOperation(value = "Retrieves the Engine Operational Status", notes = "Top-level abstraction. Provides a global view of resources", response = PolicyEngine.class) public Response engine() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager()).build(); } /** @@ -114,13 +155,14 @@ public class RestManager { response = PolicyEngine.class) public Response engineShutdown() { try { - PolicyEngine.manager.shutdown(); + PolicyEngineConstants.getManager().shutdown(); } catch (final IllegalStateException e) { - logger.error("{}: cannot shutdown {} because of {}", this, PolicyEngine.manager, e.getMessage(), e); - return Response.status(Response.Status.BAD_REQUEST).entity(PolicyEngine.manager).build(); + logger.error("{}: cannot shutdown {} because of {}", this, PolicyEngineConstants.getManager(), + e.getMessage(), e); + return Response.status(Response.Status.BAD_REQUEST).entity(PolicyEngineConstants.getManager()).build(); } - return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager()).build(); } /** @@ -133,7 +175,7 @@ public class RestManager { @ApiOperation(value = "Engine Features", notes = "Provides the list of loaded features using the PolicyEngineFeatureAPI", responseContainer = "List") public Response engineFeatures() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatures()).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getFeatures()).build(); } @GET @@ -142,7 +184,8 @@ public class RestManager { notes = "Provides detailed list of loaded features using the PolicyEngineFeatureAPI", responseContainer = "List", response = PolicyEngineFeatureApi.class) public Response engineFeaturesInventory() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatureProviders()).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getFeatureProviders()) + .build(); } /** @@ -158,8 +201,8 @@ public class RestManager { public Response engineFeature( @ApiParam(value = "Feature Name", required = true) @PathParam("featureName") String featureName) { try { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatureProvider(featureName)) - .build(); + return Response.status(Response.Status.OK) + .entity(PolicyEngineConstants.getManager().getFeatureProvider(featureName)).build(); } catch (final IllegalArgumentException iae) { logger.debug("feature unavailable: {}", featureName, iae); return Response.status(Response.Status.NOT_FOUND).entity(new Error(iae.getMessage())).build(); @@ -175,7 +218,7 @@ public class RestManager { @Path("engine/inputs") @ApiOperation(value = "Engine Input Ports", notes = "List of input ports", responseContainer = "List") public Response engineInputs() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Inputs.values())).build(); + return Response.status(Response.Status.OK).entity(INPUTS).build(); } /** @@ -193,14 +236,15 @@ public class RestManager { final PolicyController controller = null; boolean success; try { - success = PolicyEngine.manager.configure(configuration); + success = PolicyEngineConstants.getManager().configure(configuration); } catch (final Exception e) { success = false; - logger.info("{}: cannot configure {} because of {}", this, PolicyEngine.manager, e.getMessage(), e); + logger.info("{}: cannot configure {} because of {}", this, PolicyEngineConstants.getManager(), + e.getMessage(), e); } if (!success) { - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")) + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)) .build(); } else { return Response.status(Response.Status.OK).entity(controller).build(); @@ -217,7 +261,7 @@ public class RestManager { @ApiOperation(value = "Engine Configuration Properties", notes = "Used for booststrapping the engine", response = Properties.class) public Response engineProperties() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getProperties()).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getProperties()).build(); } /** @@ -230,7 +274,7 @@ public class RestManager { @ApiOperation(value = "Engine Environment Properties", notes = "Installation and OS environment properties used by the engine", response = Properties.class) public Response engineEnvironment() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getEnvironment()).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getEnvironment()).build(); } /** @@ -243,9 +287,10 @@ public class RestManager { @Consumes(MediaType.TEXT_PLAIN) @ApiOperation(value = "Gets an environment variable", response = String.class) public Response engineEnvironment( - @ApiParam(value = "Environment Property", required = true) @PathParam("envProperty") String envProperty) { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getEnvironmentProperty(envProperty)) - .build(); + @ApiParam(value = "Environment Property", + required = true) @PathParam("envProperty") String envProperty) { + return Response.status(Response.Status.OK) + .entity(PolicyEngineConstants.getManager().getEnvironmentProperty(envProperty)).build(); } /** @@ -261,7 +306,7 @@ public class RestManager { public Response engineEnvironmentAdd( @ApiParam(value = "Environment Property", required = true) @PathParam("envProperty") String envProperty, @ApiParam(value = "Environment Value", required = true) String envValue) { - final String previousValue = PolicyEngine.manager.setEnvironmentProperty(envProperty, envValue); + final String previousValue = PolicyEngineConstants.getManager().setEnvironmentProperty(envProperty, envValue); return Response.status(Response.Status.OK).entity(previousValue).build(); } @@ -275,7 +320,7 @@ public class RestManager { @ApiOperation(value = "Engine Control Switches", notes = "List of the Engine Control Switches", responseContainer = "List") public Response engineSwitches() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); + return Response.status(Response.Status.OK).entity(SWITCHES).build(); } /** @@ -292,17 +337,18 @@ public class RestManager { public Response engineActivation() { boolean success = true; try { - PolicyEngine.manager.activate(); + PolicyEngineConstants.getManager().activate(); } catch (final Exception e) { success = false; - logger.info("{}: cannot activate {} because of {}", this, PolicyEngine.manager, e.getMessage(), e); + logger.info("{}: cannot activate {} because of {}", this, PolicyEngineConstants.getManager(), + e.getMessage(), e); } if (!success) { - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")) + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)) .build(); } else { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager()).build(); } } @@ -320,17 +366,18 @@ public class RestManager { public Response engineDeactivation() { boolean success = true; try { - PolicyEngine.manager.deactivate(); + PolicyEngineConstants.getManager().deactivate(); } catch (final Exception e) { success = false; - logger.info("{}: cannot deactivate {} because of {}", this, PolicyEngine.manager, e.getMessage(), e); + logger.info("{}: cannot deactivate {} because of {}", this, PolicyEngineConstants.getManager(), + e.getMessage(), e); } if (!success) { - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")) + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)) .build(); } else { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager()).build(); } } @@ -347,11 +394,11 @@ public class RestManager { @ApiResponses(value = {@ApiResponse(code = 406, message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) public Response engineLock() { - final boolean success = PolicyEngine.manager.lock(); + final boolean success = PolicyEngineConstants.getManager().lock(); if (success) { - return Response.status(Status.OK).entity(PolicyEngine.manager).build(); + return Response.status(Status.OK).entity(PolicyEngineConstants.getManager()).build(); } else { - return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")).build(); + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)).build(); } } @@ -368,11 +415,11 @@ public class RestManager { @ApiResponses(value = {@ApiResponse(code = 406, message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) public Response engineUnlock() { - final boolean success = PolicyEngine.manager.unlock(); + final boolean success = PolicyEngineConstants.getManager().unlock(); if (success) { - return Response.status(Status.OK).entity(PolicyEngine.manager).build(); + return Response.status(Status.OK).entity(PolicyEngineConstants.getManager()).build(); } else { - return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")).build(); + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)).build(); } } @@ -386,7 +433,8 @@ public class RestManager { @ApiOperation(value = "Lists the Policy Controllers Names", notes = "Unique Policy Controller Identifiers", responseContainer = "List") public Response controllers() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getPolicyControllerIds()).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getPolicyControllerIds()) + .build(); } /** @@ -399,7 +447,8 @@ public class RestManager { @ApiOperation(value = "Lists the Policy Controllers", notes = "Detailed list of Policy Controllers", responseContainer = "List", response = PolicyController.class) public Response controllerInventory() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getPolicyControllers()).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getPolicyControllers()) + .build(); } /** @@ -424,17 +473,17 @@ public class RestManager { .build(); } - final String controllerName = config.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME); + final String controllerName = config.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME); if (controllerName == null || controllerName.isEmpty()) { return Response.status(Response.Status.BAD_REQUEST) .entity(new Error( - "Configuration must have an entry for " + DroolsProperties.PROPERTY_CONTROLLER_NAME)) + "Configuration must have an entry for " + DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME)) .build(); } PolicyController controller; try { - controller = PolicyController.factory.get(controllerName); + controller = PolicyControllerConstants.getFactory().get(controllerName); if (controller != null) { return Response.status(Response.Status.NOT_MODIFIED).entity(controller).build(); } @@ -442,14 +491,14 @@ public class RestManager { logger.trace("OK ", e); // This is OK } catch (final IllegalStateException e) { - logger.info("{}: cannot get policy-controller because of {}", this, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not found")) + logger.info(FETCH_POLICY_FAILED, this, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + NOT_FOUND_MSG)) .build(); } try { - controller = PolicyEngine.manager - .createPolicyController(config.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME), config); + controller = PolicyEngineConstants.getManager().createPolicyController( + config.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME), config); } catch (IllegalArgumentException | IllegalStateException e) { logger.warn("{}: cannot create policy-controller because of {}", this, e.getMessage(), e); return Response.status(Response.Status.BAD_REQUEST).entity(new Error(e.getMessage())).build(); @@ -480,7 +529,7 @@ public class RestManager { @ApiOperation(value = "Lists of Feature Providers Identifiers", notes = "Unique Policy Controller Identifiers", responseContainer = "List") public Response controllerFeatures() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatures()).build(); + return Response.status(Response.Status.OK).entity(PolicyEngineConstants.getManager().getFeatures()).build(); } /** @@ -494,7 +543,8 @@ public class RestManager { notes = "Provides detailed list of loaded features using the PolicyControllerFeatureAPI", responseContainer = "List", response = PolicyControllerFeatureApi.class) public Response controllerFeaturesInventory() { - return Response.status(Response.Status.OK).entity(PolicyController.factory.getFeatureProviders()).build(); + return Response.status(Response.Status.OK) + .entity(PolicyControllerConstants.getFactory().getFeatureProviders()).build(); } /** @@ -511,8 +561,9 @@ public class RestManager { public Response controllerFeature( @ApiParam(value = "Feature Name", required = true) @PathParam("featureName") String featureName) { try { - return Response.status(Response.Status.OK).entity(PolicyController.factory.getFeatureProvider(featureName)) - .build(); + return Response.status(Response.Status.OK) + .entity(PolicyControllerConstants.getFactory().getFeatureProvider(featureName)) + .build(); } catch (final IllegalArgumentException iae) { logger.debug("{}: cannot feature {} because of {}", this, featureName, iae.getMessage(), iae); return Response.status(Response.Status.NOT_FOUND).entity(new Error(iae.getMessage())).build(); @@ -537,14 +588,15 @@ public class RestManager { public Response controller(@ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName) { try { - return Response.status(Response.Status.OK).entity(PolicyController.factory.get(controllerName)).build(); + return Response.status(Response.Status.OK) + .entity(PolicyControllerConstants.getFactory().get(controllerName)).build(); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) - .build(); + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); } } @@ -569,23 +621,23 @@ public class RestManager { PolicyController controller; try { - controller = PolicyController.factory.get(controllerName); + controller = PolicyControllerConstants.getFactory().get(controllerName); if (controller == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + " does not exist")).build(); + .entity(new Error(controllerName + DOES_NOT_EXIST_MSG)).build(); } } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + " not found: " + e.getMessage())).build(); + .entity(new Error(controllerName + NOT_FOUND + e.getMessage())).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) - .build(); + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); } try { - PolicyEngine.manager.removePolicyController(controllerName); + PolicyEngineConstants.getManager().removePolicyController(controllerName); } catch (IllegalArgumentException | IllegalStateException e) { logger.debug("{}: cannot remove policy-controller {} because of {}", this, controllerName, e.getMessage(), e); @@ -611,15 +663,15 @@ public class RestManager { public Response controllerProperties(@ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName) { try { - final PolicyController controller = PolicyController.factory.get(controllerName); + final PolicyController controller = PolicyControllerConstants.getFactory().get(controllerName); return Response.status(Response.Status.OK).entity(controller.getProperties()).build(); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) - .build(); + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); } } @@ -632,7 +684,7 @@ public class RestManager { @Path("engine/controllers/{controller}/inputs") @ApiOperation(value = "Policy Controller Input Ports", notes = "List of input ports", responseContainer = "List") public Response controllerInputs() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Inputs.values())).build(); + return Response.status(Response.Status.OK).entity(INPUTS).build(); } /** @@ -659,21 +711,21 @@ public class RestManager { PolicyController controller; try { - controller = PolicyEngine.manager.updatePolicyController(controllerConfiguration); + controller = PolicyEngineConstants.getManager().updatePolicyController(controllerConfiguration); if (controller == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + " does not exist")).build(); + .entity(new Error(controllerName + DOES_NOT_EXIST_MSG)).build(); } } catch (final IllegalArgumentException e) { logger.info("{}: cannot update policy-controller {} because of {}", this, controllerName, e.getMessage(), e); return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + " not found: " + e.getMessage())).build(); + .entity(new Error(controllerName + NOT_FOUND + e.getMessage())).build(); } catch (final Exception e) { logger.info("{}: cannot update policy-controller {} because of {}", this, controllerName, e.getMessage(), - e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) - .build(); + e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); } return Response.status(Response.Status.OK).entity(controller).build(); @@ -689,7 +741,7 @@ public class RestManager { @ApiOperation(value = "Policy Controller Switches", notes = "List of the Policy Controller Switches", responseContainer = "List") public Response controllerSwitches() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); + return Response.status(Response.Status.OK).entity(SWITCHES).build(); } /** @@ -705,7 +757,7 @@ public class RestManager { message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) public Response controllerLock(@ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName) { - final PolicyController policyController = PolicyController.factory.get(controllerName); + final PolicyController policyController = PolicyControllerConstants.getFactory().get(controllerName); final boolean success = policyController.lock(); if (success) { return Response.status(Status.OK).entity(policyController).build(); @@ -728,7 +780,7 @@ public class RestManager { message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) public Response controllerUnlock(@ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName) { - final PolicyController policyController = PolicyController.factory.get(controllerName); + final PolicyController policyController = PolicyControllerConstants.getFactory().get(controllerName); final boolean success = policyController.unlock(); if (success) { return Response.status(Status.OK).entity(policyController).build(); @@ -757,12 +809,12 @@ public class RestManager { final DroolsController drools = this.getDroolsController(controllerName); return Response.status(Response.Status.OK).entity(drools).build(); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + logger.debug(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) - .build(); + logger.debug(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); } } @@ -789,12 +841,12 @@ public class RestManager { } return Response.status(Response.Status.OK).entity(sessionCounts).build(); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) - .build(); + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); } } @@ -818,12 +870,12 @@ public class RestManager { final DroolsController drools = this.getDroolsController(controllerName); return Response.status(Response.Status.OK).entity(drools.factClassNames(sessionName)).build(); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, e.getMessage(), e); + logger.debug(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND).entity(new Error("entity not found")).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, e.getMessage(), e); + logger.debug(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + sessionName + " not acceptable")).build(); + .entity(new Error(controllerName + ":" + sessionName + NOT_ACCEPTABLE_MSG)).build(); } } @@ -856,13 +908,14 @@ public class RestManager { return Response.status(Response.Status.OK).entity(facts.size()).build(); } } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + sessionName + ":" + factType + " not found")).build(); + .entity(new Error(controllerName + ":" + sessionName + ":" + factType + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + sessionName + ":" + factType + " not acceptable")).build(); + .entity(new Error(controllerName + ":" + sessionName + ":" + factType + NOT_ACCEPTABLE_MSG)) + .build(); } } @@ -899,21 +952,21 @@ public class RestManager { return Response.status(Response.Status.OK).entity(facts.size()).build(); } } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}", this, + logger.debug(FETCH_DROOLS_BY_ENTITY_FAILED, this, controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not found")) + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + NOT_FOUND_MSG)) .build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}", this, + logger.debug(FETCH_DROOLS_BY_ENTITY_FAILED, this, controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not acceptable")) + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + NOT_ACCEPTABLE_MSG)) .build(); } catch (final Exception e) { - logger.debug("{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}", this, + logger.debug(FETCH_DROOLS_BY_ENTITY_FAILED, this, controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); } @@ -954,23 +1007,23 @@ public class RestManager { return Response.status(Response.Status.OK).entity(facts).build(); } catch (final IllegalArgumentException e) { logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + FETCH_DROOLS_BY_PARAMS_FAILED, this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not found")) + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + NOT_FOUND_MSG)) .build(); } catch (final IllegalStateException e) { logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + FETCH_DROOLS_BY_PARAMS_FAILED, this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not acceptable")) + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + NOT_ACCEPTABLE_MSG)) .build(); } catch (final Exception e) { logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + FETCH_DROOLS_BY_PARAMS_FAILED, this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); } @@ -1002,17 +1055,18 @@ public class RestManager { final List<Object> facts = drools.facts(sessionName, factType, true); return Response.status(Response.Status.OK).entity(facts).build(); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get: drools-controller {}, session {}, factType {}, because of {}", this, + logger.debug(FETCH_DROOLS_BY_FACTTYPE_FAILED, this, controllerName, sessionName, factType, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + sessionName + ":" + factType + " not found")).build(); + .entity(new Error(controllerName + ":" + sessionName + ":" + factType + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get: drools-controller {}, session {}, factType {}, because of {}", this, - controllerName, sessionName, factType, e.getMessage(), e); + logger.debug(FETCH_DROOLS_BY_FACTTYPE_FAILED, this, + controllerName, sessionName, factType, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + sessionName + ":" + factType + " not acceptable")).build(); + .entity(new Error(controllerName + ":" + sessionName + ":" + factType + NOT_ACCEPTABLE_MSG)) + .build(); } catch (final Exception e) { - logger.debug("{}: cannot get: drools-controller {}, session {}, factType {}, because of {}", this, + logger.debug(FETCH_DROOLS_BY_FACTTYPE_FAILED, this, controllerName, sessionName, factType, e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); } @@ -1054,23 +1108,23 @@ public class RestManager { return Response.status(Response.Status.OK).entity(facts).build(); } catch (final IllegalArgumentException e) { logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + FETCH_DROOLS_BY_PARAMS_FAILED, this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not found")) + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + NOT_FOUND_MSG)) .build(); } catch (final IllegalStateException e) { logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + FETCH_DROOLS_BY_PARAMS_FAILED, this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not acceptable")) + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + NOT_ACCEPTABLE_MSG)) .build(); } catch (final Exception e) { logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + FETCH_DROOLS_BY_PARAMS_FAILED, this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); } @@ -1111,17 +1165,17 @@ public class RestManager { try { final DroolsController drools = this.getDroolsController(controllerName); final List<ProtocolCoderToolset> decoders = - EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId()); + EventProtocolCoderConstants.getManager().getDecoders(drools.getGroupId(), drools.getArtifactId()); return Response.status(Response.Status.OK).entity(decoders).build(); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, controllerName, + logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) - .build(); + logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, + e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); } } @@ -1146,18 +1200,18 @@ public class RestManager { required = true) @PathParam("controller") String controllerName) { try { final DroolsController drools = this.getDroolsController(controllerName); - final List<CoderFilters> filters = - EventProtocolCoder.manager.getDecoderFilters(drools.getGroupId(), drools.getArtifactId()); + final List<CoderFilters> filters = EventProtocolCoderConstants.getManager() + .getDecoderFilters(drools.getGroupId(), drools.getArtifactId()); return Response.status(Response.Status.OK).entity(filters).build(); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, controllerName, + logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) - .build(); + logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, + e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); } } @@ -1182,19 +1236,19 @@ public class RestManager { @ApiParam(value = "Networked Topic Name", required = true) @PathParam("topic") String topic) { try { final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = - EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() + .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); return Response.status(Response.Status.OK).entity(decoder).build(); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + " not found")).build(); + .entity(new Error(controllerName + ":" + topic + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + " not acceptable")).build(); + .entity(new Error(controllerName + ":" + topic + NOT_ACCEPTABLE_MSG)).build(); } } @@ -1220,24 +1274,24 @@ public class RestManager { @ApiParam(value = "Networked Topic Name", required = true) @PathParam("topic") String topic) { try { final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = - EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() + .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); if (decoder == null) { - return Response.status(Response.Status.BAD_REQUEST).entity(new Error(topic + " does not exist")) + return Response.status(Response.Status.BAD_REQUEST).entity(new Error(topic + DOES_NOT_EXIST_MSG)) .build(); } else { return Response.status(Response.Status.OK).entity(decoder.getCoders()).build(); } } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + " not found")).build(); + .entity(new Error(controllerName + ":" + topic + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + " not acceptable")).build(); + .entity(new Error(controllerName + ":" + topic + NOT_ACCEPTABLE_MSG)).build(); } } @@ -1264,25 +1318,25 @@ public class RestManager { @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass) { try { final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = - EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() + .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); final CoderFilters filters = decoder.getCoder(factClass); if (filters == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(topic + ":" + factClass + " does not exist")).build(); + .entity(new Error(topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build(); } else { return Response.status(Response.Status.OK).entity(filters).build(); } } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", this, + logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this, controllerName, topic, factClass, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", this, + logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this, controllerName, topic, factClass, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_ACCEPTABLE_MSG)).build(); } } @@ -1318,27 +1372,27 @@ public class RestManager { try { final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = - EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() + .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); final CoderFilters filters = decoder.getCoder(factClass); if (filters == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(topic + ":" + factClass + " does not exist")).build(); + .entity(new Error(topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build(); } filters.setFilter(configFilters); return Response.status(Response.Status.OK).entity(filters).build(); } catch (final IllegalArgumentException e) { logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} filters {} because of {}", + FETCH_DECODER_BY_FILTER_FAILED, this, controllerName, topic, factClass, configFilters, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} filters {} because of {}", + FETCH_DECODER_BY_FILTER_FAILED, this, controllerName, topic, factClass, configFilters, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_ACCEPTABLE_MSG)).build(); } } @@ -1363,32 +1417,32 @@ public class RestManager { @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass) { try { final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = - EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() + .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); final CoderFilters filters = decoder.getCoder(factClass); if (filters == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build(); } final JsonProtocolFilter filter = filters.getFilter(); if (filter == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NO_FILTERS)).build(); } return Response.status(Response.Status.OK).entity(filter.getRule()).build(); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", this, + logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this, controllerName, topic, factClass, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", this, + logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this, controllerName, topic, factClass, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_ACCEPTABLE_MSG)).build(); } } @@ -1415,37 +1469,37 @@ public class RestManager { try { final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = - EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() + .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); final CoderFilters filters = decoder.getCoder(factClass); if (filters == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build(); } final JsonProtocolFilter filter = filters.getFilter(); if (filter == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NO_FILTERS)).build(); } filter.setRule(null); return Response.status(Response.Status.OK).entity(filter.getRule()).build(); } catch (final IllegalArgumentException e) { logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", + FETCH_DECODER_BY_TYPE_FAILED, this, controllerName, topic, factClass, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_FOUND_MSG)) .build(); } catch (final IllegalStateException e) { logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", + FETCH_DECODER_BY_TYPE_FAILED, this, controllerName, topic, factClass, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) .entity(new Error( - controllerName + ":" + topic + ":" + factClass + " not acceptable")) + controllerName + ":" + topic + ":" + factClass + NOT_ACCEPTABLE_MSG)) .build(); } } @@ -1473,19 +1527,19 @@ public class RestManager { try { final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = - EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() + .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); final CoderFilters filters = decoder.getCoder(factClass); if (filters == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build(); } final JsonProtocolFilter filter = filters.getFilter(); if (filter == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NO_FILTERS)).build(); } if (rule == null || rule.isEmpty()) { @@ -1501,14 +1555,14 @@ public class RestManager { + "topic {} type {} because of {}", this, controllerName, topic, factClass, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + " not found")).build(); + .entity(new Error(controllerName + ":" + topic + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { logger.debug( "{}: cannot access decoder filter rules for policy-controller {} " + "topic {} type {} because of {}", this, controllerName, topic, factClass, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_ACCEPTABLE_MSG)).build(); } } @@ -1532,17 +1586,17 @@ public class RestManager { PolicyController policyController; try { - policyController = PolicyController.factory.get(controllerName); + policyController = PolicyControllerConstants.getFactory().get(controllerName); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + " not found")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + NOT_FOUND_MSG)).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + " not acceptable")).build(); + .entity(new Error(controllerName + ":" + topic + ":" + NOT_ACCEPTABLE_MSG)).build(); } final CodingResult result = new CodingResult(); @@ -1552,17 +1606,17 @@ public class RestManager { Object event; try { - event = EventProtocolCoder.manager.decode(policyController.getDrools().getGroupId(), + event = EventProtocolCoderConstants.getManager().decode(policyController.getDrools().getGroupId(), policyController.getDrools().getArtifactId(), topic, json); result.setDecoding(true); } catch (final Exception e) { - logger.debug("{}: cannot get policy-controller {} topic {} because of {}", this, controllerName, topic, + logger.debug(FETCH_POLICY_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e); return Response.status(Response.Status.BAD_REQUEST).entity(new Error(e.getMessage())).build(); } try { - result.setJsonEncoding(EventProtocolCoder.manager.encode(topic, event)); + result.setJsonEncoding(EventProtocolCoderConstants.getManager().encode(topic, event)); result.setEncoding(true); } catch (final Exception e) { // continue so to propagate decoding results .. @@ -1589,16 +1643,17 @@ public class RestManager { required = true) @PathParam("controller") String controllerName) { List<CoderFilters> encoders; try { - final PolicyController controller = PolicyController.factory.get(controllerName); + final PolicyController controller = PolicyControllerConstants.getFactory().get(controllerName); final DroolsController drools = controller.getDrools(); - encoders = EventProtocolCoder.manager.getEncoderFilters(drools.getGroupId(), drools.getArtifactId()); + encoders = EventProtocolCoderConstants.getManager().getEncoderFilters(drools.getGroupId(), + drools.getArtifactId()); } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get encoder filters for policy-controller {} because of {}", this, controllerName, + logger.debug(FETCH_ENCODER_BY_FILTER_FAILED, this, controllerName, e.getMessage(), e); return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + " not found: " + e.getMessage())).build(); + .entity(new Error(controllerName + NOT_FOUND + e.getMessage())).build(); } catch (final IllegalStateException e) { - logger.debug("{}: cannot get encoder filters for policy-controller {} because of {}", this, controllerName, + logger.debug(FETCH_ENCODER_BY_FILTER_FAILED, this, controllerName, e.getMessage(), e); return Response.status(Response.Status.NOT_ACCEPTABLE) .entity(new Error(controllerName + " is not accepting the request")).build(); @@ -1620,7 +1675,7 @@ public class RestManager { @ApiOperation(value = "Topics Control Switches", notes = "List of the Topic Control Switches", responseContainer = "List") public Response topicSwitches() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); + return Response.status(Response.Status.OK).entity(SWITCHES).build(); } /** @@ -1639,7 +1694,7 @@ public class RestManager { if (success) { return Response.status(Status.OK).entity(TopicEndpointManager.getManager()).build(); } else { - return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")).build(); + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)).build(); } } @@ -1659,7 +1714,7 @@ public class RestManager { if (success) { return Response.status(Status.OK).entity(TopicEndpointManager.getManager()).build(); } else { - return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")).build(); + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error(CANNOT_PERFORM_OPERATION)).build(); } } @@ -1832,7 +1887,7 @@ public class RestManager { public Response commSourceTopicSwitches( @ApiParam(value = "Communication Mechanism", required = true) @PathParam("comm") String comm ) { - return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); + return Response.status(Response.Status.OK).entity(SWITCHES).build(); } /** @@ -1845,7 +1900,7 @@ public class RestManager { public Response commSinkTopicSwitches( @ApiParam(value = "Communication Mechanism", required = true) @PathParam("comm") String comm ) { - return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); + return Response.status(Response.Status.OK).entity(SWITCHES).build(); } /** @@ -2028,9 +2083,13 @@ public class RestManager { .build(); } } catch (IllegalArgumentException e) { + logger.debug("{}: cannot offer to topic {} because of {}", this, topic, e.getMessage(), + e); return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(topic + " not found")).build(); + .entity(new Error(topic + NOT_FOUND_MSG)).build(); } catch (IllegalStateException e) { + logger.debug("{}: cannot offer to topic {} because of {}", this, topic, e.getMessage(), + e); return Response.status(Response.Status.NOT_ACCEPTABLE) .entity(new Error(topic + " not acceptable due to current state")) .build(); @@ -2144,14 +2203,14 @@ public class RestManager { * @throws IllegalArgumentException if an invalid controller name has been passed in */ protected DroolsController getDroolsController(String controllerName) { - final PolicyController controller = PolicyController.factory.get(controllerName); + final PolicyController controller = PolicyControllerConstants.getFactory().get(controllerName); if (controller == null) { - throw new IllegalArgumentException(controllerName + " does not exist"); + throw new IllegalArgumentException(controllerName + DOES_NOT_EXIST_MSG); } final DroolsController drools = controller.getDrools(); if (drools == null) { - throw new IllegalArgumentException(controllerName + " has no drools configuration"); + throw new IllegalArgumentException(controllerName + " has no drools configuration"); } return drools; @@ -2229,19 +2288,5 @@ public class RestManager { this.msg = msg; } } - - /** - * Feed Ports into Resources. - */ - public enum Inputs { - configuration, - } - - /** - * Resource Toggles. - */ - public enum Switches { - activation, lock, - } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/server/restful/aaf/AafBase.java b/policy-management/src/main/java/org/onap/policy/drools/server/restful/aaf/AafBase.java index 955fb242..67725955 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/server/restful/aaf/AafBase.java +++ b/policy-management/src/main/java/org/onap/policy/drools/server/restful/aaf/AafBase.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ package org.onap.policy.drools.server.restful.aaf; import org.onap.policy.common.endpoints.http.server.aaf.AafAuthFilter; -import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.system.PolicyEngineConstants; /** * AAF Base Class. @@ -30,6 +30,6 @@ public abstract class AafBase extends AafAuthFilter { public static final String AAF_NODETYPE = "pdpd"; public static final String AAF_ROOT_PERMISSION_PROPERTY = "aaf.root.permission"; public static final String AAF_ROOT_PERMISSION = - PolicyEngine.manager.getProperties().getProperty( + PolicyEngineConstants.getManager().getProperties().getProperty( AAF_ROOT_PERMISSION_PROPERTY, DEFAULT_NAMESPACE + "." + AAF_NODETYPE); } diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/IndexedPolicyControllerFactory.java b/policy-management/src/main/java/org/onap/policy/drools/system/IndexedPolicyControllerFactory.java index 38085101..0d7806c6 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/IndexedPolicyControllerFactory.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/IndexedPolicyControllerFactory.java @@ -29,6 +29,7 @@ import java.util.Properties; import org.onap.policy.common.gson.annotation.GsonJsonIgnore; import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.features.PolicyControllerFeatureApi; +import org.onap.policy.drools.features.PolicyControllerFeatureApiConstants; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; import org.onap.policy.drools.system.internal.AggregatedPolicyController; import org.slf4j.Logger; @@ -382,6 +383,6 @@ class IndexedPolicyControllerFactory implements PolicyControllerFactory { } protected List<PolicyControllerFeatureApi> getProviders() { - return PolicyControllerFeatureApi.providers.getList(); + return PolicyControllerFeatureApiConstants.getProviders().getList(); } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/Main.java b/policy-management/src/main/java/org/onap/policy/drools/system/Main.java index 11ffd689..1ef578c1 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/Main.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/Main.java @@ -22,8 +22,8 @@ package org.onap.policy.drools.system; import java.util.Properties; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; -import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.DroolsProperties; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; +import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.utils.PropertyUtil; import org.onap.policy.drools.utils.logging.LoggerUtil; import org.onap.policy.drools.utils.logging.MdcTransaction; @@ -51,35 +51,35 @@ public class Main { /* system properties */ - for (Properties systemProperties : SystemPersistence.manager.getSystemProperties()) { + for (Properties systemProperties : SystemPersistenceConstants.getManager().getSystemProperties()) { PropertyUtil.setSystemProperties(systemProperties); } /* 0. boot */ - PolicyEngine.manager.boot(args); + PolicyEngineConstants.getManager().boot(args); /* 1.a. Configure Engine */ Properties engineProperties; try { - engineProperties = SystemPersistence.manager.getEngineProperties(); + engineProperties = SystemPersistenceConstants.getManager().getEngineProperties(); } catch (IllegalArgumentException iae) { logger.warn("Main: engine properties not found. Using default configuration.", iae); - engineProperties = PolicyEngine.manager.defaultTelemetryConfig(); + engineProperties = PolicyEngineConstants.getManager().defaultTelemetryConfig(); } - PolicyEngine.manager.configure(engineProperties); + PolicyEngineConstants.getManager().configure(engineProperties); /* 1.b. Load Installation Environment(s) */ - for (Properties env : SystemPersistence.manager.getEnvironmentProperties()) { - PolicyEngine.manager.setEnvironment(env); + for (Properties env : SystemPersistenceConstants.getManager().getEnvironmentProperties()) { + PolicyEngineConstants.getManager().setEnvironment(env); } /* 2. Add topics */ - for (Properties topicProperties : SystemPersistence.manager.getTopicProperties()) { + for (Properties topicProperties : SystemPersistenceConstants.getManager().getTopicProperties()) { TopicEndpointManager.getManager().addTopics(topicProperties); } @@ -91,13 +91,13 @@ public class Main { .setTargetEntity("engine") .setTargetServiceName("start"); try { - final boolean success = PolicyEngine.manager.start(); + final boolean success = PolicyEngineConstants.getManager().start(); if (!success) { trans.setStatusCode(false).setResponseDescription("partial start").flush(); logger.warn( LoggerUtil.TRANSACTION_LOG_MARKER, "Main: {} has been partially started", - PolicyEngine.manager); + PolicyEngineConstants.getManager()); } else { trans.setStatusCode(true).transaction(); } @@ -110,7 +110,7 @@ public class Main { logger.warn( LoggerUtil.TRANSACTION_LOG_MARKER, "Main: cannot start {} (bad state) because of {}", - PolicyEngine.manager, + PolicyEngineConstants.getManager(), e.getMessage(), e); } catch (final Exception e) { @@ -122,7 +122,7 @@ public class Main { logger.warn( LoggerUtil.TRANSACTION_LOG_MARKER, "Main: cannot start {} because of {}", - PolicyEngine.manager, + PolicyEngineConstants.getManager(), e.getMessage(), e); System.exit(1); @@ -131,9 +131,9 @@ public class Main { /* 4. Create and start the controllers */ for (final Properties controllerProperties : - SystemPersistence.manager.getControllerProperties()) { + SystemPersistenceConstants.getManager().getControllerProperties()) { final String controllerName = - controllerProperties.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME); + controllerProperties.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME); try { trans = MdcTransaction.newTransaction(null, null) @@ -142,7 +142,7 @@ public class Main { .setTargetServiceName("start"); final PolicyController controller = - PolicyEngine.manager.createPolicyController(controllerName, controllerProperties); + PolicyEngineConstants.getManager().createPolicyController(controllerName, controllerProperties); controller.start(); trans diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyController.java b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyController.java index 9bc75b39..17247f41 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyController.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -41,11 +41,6 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifi public interface PolicyController extends Startable, Lockable { /** - * Factory that tracks and manages Policy Controllers. - */ - static PolicyControllerFactory factory = new IndexedPolicyControllerFactory(); - - /** * name of this Policy Controller. */ String getName(); @@ -72,7 +67,7 @@ public interface PolicyController extends Startable, Lockable { /** * Update maven configuration. - * + * * @param newDroolsConfiguration new drools configuration * @return true if the update was successful, false otherwise */ @@ -90,11 +85,11 @@ public interface PolicyController extends Startable, Lockable { /** * Attempts delivering of an String over communication infrastructure "busType". - * + * * @param busType bus type * @param topic topic * @param event Communication infrastructure identifier - * + * * @return true if successful, false if a failure has occurred. * @throws IllegalArgumentException when invalid or insufficient properties are provided * @throws IllegalStateException when the engine is in a state where this operation is not @@ -106,7 +101,7 @@ public interface PolicyController extends Startable, Lockable { /** * halts and permanently releases all resources. - * + * * @throws IllegalStateException throws illegal state exception */ void halt(); diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyControllerConstants.java b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyControllerConstants.java new file mode 100644 index 00000000..78d24129 --- /dev/null +++ b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyControllerConstants.java @@ -0,0 +1,36 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.system; + +import lombok.Getter; + +public class PolicyControllerConstants { + + /** + * Factory that tracks and manages Policy Controllers. + */ + @Getter + private static final PolicyControllerFactory factory = new IndexedPolicyControllerFactory(); + + private PolicyControllerConstants() { + // do nothing + } +} diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngine.java b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngine.java index eb2ed3df..506474cb 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngine.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngine.java @@ -46,25 +46,6 @@ import org.onap.policy.drools.protocol.configuration.PdpdConfiguration; * RestTopicWriter <br> PolicyEngine 1 --- 1 ManagementServer */ public interface PolicyEngine extends Startable, Lockable, TopicListener { - /** - * Policy Engine Manager. - */ - PolicyEngine manager = new PolicyEngineManager(); - - /** - * Default Telemetry Server Port. - */ - int TELEMETRY_SERVER_DEFAULT_PORT = 9696; - - /** - * Default Telemetry Server Hostname. - */ - String TELEMETRY_SERVER_DEFAULT_HOST = "localhost"; - - /** - * Default Telemetry Server Name. - */ - String TELEMETRY_SERVER_DEFAULT_NAME = "TELEMETRY"; /** * Boot the engine. diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineConstants.java b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineConstants.java new file mode 100644 index 00000000..4d18d6b8 --- /dev/null +++ b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineConstants.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * policy-management + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.system; + +import lombok.Getter; + +public class PolicyEngineConstants { + + /** + * Default Telemetry Server Port. + */ + public static final int TELEMETRY_SERVER_DEFAULT_PORT = 9696; + + /** + * Default Telemetry Server Hostname. + */ + public static final String TELEMETRY_SERVER_DEFAULT_HOST = "localhost"; + + /** + * Default Telemetry Server Name. + */ + public static final String TELEMETRY_SERVER_DEFAULT_NAME = "TELEMETRY"; + + /** + * Policy Engine Manager. + */ + @Getter + private static final PolicyEngine manager = new PolicyEngineManager(); + + private PolicyEngineConstants() { + // do nothing + } +} diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.java b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.java index 1c02d705..36d8ca59 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.java @@ -20,6 +20,10 @@ package org.onap.policy.drools.system; +import static org.onap.policy.drools.system.PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_HOST; +import static org.onap.policy.drools.system.PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_NAME; +import static org.onap.policy.drools.system.PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_PORT; + import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.Gson; @@ -40,13 +44,18 @@ import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.common.gson.annotation.GsonJsonIgnore; import org.onap.policy.common.gson.annotation.GsonJsonProperty; import org.onap.policy.drools.controller.DroolsController; +import org.onap.policy.drools.controller.DroolsControllerConstants; import org.onap.policy.drools.core.PolicyContainer; import org.onap.policy.drools.core.jmx.PdpJmxListener; import org.onap.policy.drools.features.PolicyControllerFeatureApi; +import org.onap.policy.drools.features.PolicyControllerFeatureApiConstants; import org.onap.policy.drools.features.PolicyEngineFeatureApi; +import org.onap.policy.drools.features.PolicyEngineFeatureApiConstants; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.DroolsProperties; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; +import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants; import org.onap.policy.drools.protocol.configuration.ControllerConfiguration; import org.onap.policy.drools.protocol.configuration.PdpdConfiguration; import org.onap.policy.drools.server.restful.RestManager; @@ -279,16 +288,17 @@ class PolicyEngineManager implements PolicyEngine { .setTargetEntity(config.getEntity()); } - switch (entity) { - case PdpdConfiguration.CONFIG_ENTITY_CONTROLLER: - boolean success = controllerConfig(config); - mdcTrans.resetSubTransaction().setStatusCode(success).transaction(); - return success; - default: - final String msg = "Configuration Entity is not supported: " + entity; - mdcTrans.resetSubTransaction().setStatusCode(false).setResponseDescription(msg).flush(); - logger.warn(LoggerUtil.TRANSACTION_LOG_MARKER_NAME, msg); - throw new IllegalArgumentException(msg); + + if (PdpdConfiguration.CONFIG_ENTITY_CONTROLLER.equals(entity)) { + boolean success = controllerConfig(config); + mdcTrans.resetSubTransaction().setStatusCode(success).transaction(); + return success; + + } else { + final String msg = "Configuration Entity is not supported: " + entity; + mdcTrans.resetSubTransaction().setStatusCode(false).setResponseDescription(msg).flush(); + logger.warn(LoggerUtil.TRANSACTION_LOG_MARKER_NAME, msg); + throw new IllegalArgumentException(msg); } } @@ -299,7 +309,7 @@ class PolicyEngineManager implements PolicyEngine { // check if a PROPERTY_CONTROLLER_NAME property is present // if so, override the given name - final String propertyControllerName = properties.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME); + final String propertyControllerName = properties.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME); if (propertyControllerName != null && !propertyControllerName.isEmpty()) { if (!propertyControllerName.equals(tempName)) { throw new IllegalStateException("Proposed name (" + tempName + ") and properties name (" @@ -425,12 +435,15 @@ class PolicyEngineManager implements PolicyEngine { controllerName); /* - * try to bring up bad controller in brainless mode, after having it working, apply - * the new create/update operation. + * try to bring up bad controller in brainless mode, after having it + * working, apply the new create/update operation. */ - controllerProperties.setProperty(DroolsProperties.RULES_GROUPID, DroolsController.NO_GROUP_ID); - controllerProperties.setProperty(DroolsProperties.RULES_ARTIFACTID, DroolsController.NO_ARTIFACT_ID); - controllerProperties.setProperty(DroolsProperties.RULES_VERSION, DroolsController.NO_VERSION); + controllerProperties.setProperty(DroolsPropertyConstants.RULES_GROUPID, + DroolsControllerConstants.NO_GROUP_ID); + controllerProperties.setProperty(DroolsPropertyConstants.RULES_ARTIFACTID, + DroolsControllerConstants.NO_ARTIFACT_ID); + controllerProperties.setProperty(DroolsPropertyConstants.RULES_VERSION, + DroolsControllerConstants.NO_VERSION); policyController = getPolicyEngine().createPolicyController(controllerName, controllerProperties); @@ -1272,11 +1285,11 @@ class PolicyEngineManager implements PolicyEngine { // these methods may be overridden by junit tests protected List<PolicyEngineFeatureApi> getEngineProviders() { - return PolicyEngineFeatureApi.providers.getList(); + return PolicyEngineFeatureApiConstants.getProviders().getList(); } protected List<PolicyControllerFeatureApi> getControllerProviders() { - return PolicyControllerFeatureApi.providers.getList(); + return PolicyControllerFeatureApiConstants.getProviders().getList(); } protected void globalInitContainer(String[] cliArgs) { @@ -1292,7 +1305,7 @@ class PolicyEngineManager implements PolicyEngine { } protected PolicyControllerFactory getControllerFactory() { - return PolicyController.factory; + return PolicyControllerConstants.getFactory(); } protected void startPdpJmxListener() { @@ -1308,14 +1321,14 @@ class PolicyEngineManager implements PolicyEngine { } protected EventProtocolCoder getProtocolCoder() { - return EventProtocolCoder.manager; + return EventProtocolCoderConstants.getManager(); } protected SystemPersistence getPersistenceManager() { - return SystemPersistence.manager; + return SystemPersistenceConstants.getManager(); } protected PolicyEngine getPolicyEngine() { - return PolicyEngine.manager; + return PolicyEngineConstants.getManager(); } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java b/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java index 51280eb3..5d915104 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java @@ -35,10 +35,13 @@ import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.common.endpoints.event.comm.TopicSource; import org.onap.policy.common.gson.annotation.GsonJsonIgnore; import org.onap.policy.drools.controller.DroolsController; +import org.onap.policy.drools.controller.DroolsControllerConstants; import org.onap.policy.drools.controller.DroolsControllerFactory; import org.onap.policy.drools.features.PolicyControllerFeatureApi; +import org.onap.policy.drools.features.PolicyControllerFeatureApiConstants; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.DroolsProperties; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; +import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; import org.onap.policy.drools.system.PolicyController; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; @@ -148,14 +151,15 @@ public class AggregatedPolicyController implements PolicyController, TopicListen return droolsController .getBaseDomainNames() .stream() - .map(d -> new ToscaPolicyTypeIdentifier(d, DroolsProperties.DEFAULT_CONTROLLER_POLICY_TYPE_VERSION)) + .map(d -> new ToscaPolicyTypeIdentifier(d, + DroolsPropertyConstants.DEFAULT_CONTROLLER_POLICY_TYPE_VERSION)) .collect(Collectors.toList()); } protected List<ToscaPolicyTypeIdentifier> getPolicyTypesFromProperties() { List<ToscaPolicyTypeIdentifier> policyTypeIds = new ArrayList<>(); - String ptiPropValue = properties.getProperty(DroolsProperties.PROPERTY_CONTROLLER_POLICY_TYPES); + String ptiPropValue = properties.getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_POLICY_TYPES); if (ptiPropValue == null) { return policyTypeIds; } @@ -165,7 +169,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen String[] ptv = pti.split(":"); if (ptv.length == 1) { policyTypeIds.add(new ToscaPolicyTypeIdentifier(ptv[0], - DroolsProperties.DEFAULT_CONTROLLER_POLICY_TYPE_VERSION)); + DroolsPropertyConstants.DEFAULT_CONTROLLER_POLICY_TYPE_VERSION)); } else if (ptv.length == 2) { policyTypeIds.add(new ToscaPolicyTypeIdentifier(ptv[0], ptv[1])); } @@ -221,9 +225,10 @@ public class AggregatedPolicyController implements PolicyController, TopicListen try { /* Drools Controller created, update initialization properties for restarts */ - this.properties.setProperty(DroolsProperties.RULES_GROUPID, newDroolsConfiguration.getGroupId()); - this.properties.setProperty(DroolsProperties.RULES_ARTIFACTID, newDroolsConfiguration.getArtifactId()); - this.properties.setProperty(DroolsProperties.RULES_VERSION, newDroolsConfiguration.getVersion()); + this.properties.setProperty(DroolsPropertyConstants.RULES_GROUPID, newDroolsConfiguration.getGroupId()); + this.properties.setProperty(DroolsPropertyConstants.RULES_ARTIFACTID, + newDroolsConfiguration.getArtifactId()); + this.properties.setProperty(DroolsPropertyConstants.RULES_VERSION, newDroolsConfiguration.getVersion()); getPersistenceManager().storeController(name, this.properties); @@ -719,7 +724,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen // the following methods may be overridden by junit tests protected SystemPersistence getPersistenceManager() { - return SystemPersistence.manager; + return SystemPersistenceConstants.getManager(); } protected TopicEndpoint getEndpointManager() { @@ -727,11 +732,11 @@ public class AggregatedPolicyController implements PolicyController, TopicListen } protected DroolsControllerFactory getDroolsFactory() { - return DroolsController.factory; + return DroolsControllerConstants.getFactory(); } protected List<PolicyControllerFeatureApi> getProviders() { - return PolicyControllerFeatureApi.providers.getList(); + return PolicyControllerFeatureApiConstants.getProviders().getList(); } } diff --git a/policy-management/src/test/java/org/onap/policy/drools/controller/DroolsControllerFactoryTest.java b/policy-management/src/test/java/org/onap/policy/drools/controller/DroolsControllerFactoryTest.java index 47baa07e..67026c0a 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/controller/DroolsControllerFactoryTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/controller/DroolsControllerFactoryTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-management * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ public class DroolsControllerFactoryTest { @Test public void buildNullController() { Properties droolsProps = new Properties(); - DroolsController droolsController = DroolsController.factory.build(droolsProps, null, null); + DroolsController droolsController = DroolsControllerConstants.getFactory().build(droolsProps, null, null); if (!isNullController(droolsController)) { fail("drools controller is not a null controller"); @@ -44,20 +44,20 @@ public class DroolsControllerFactoryTest { @Test public void getNullController() { DroolsController controller = - DroolsController.factory.get(DroolsController.NO_GROUP_ID, - DroolsController.NO_ARTIFACT_ID, DroolsController.NO_VERSION); + DroolsControllerConstants.getFactory().get(DroolsControllerConstants.NO_GROUP_ID, + DroolsControllerConstants.NO_ARTIFACT_ID, DroolsControllerConstants.NO_VERSION); assertNotNull(controller); - assertEquals(DroolsController.NO_GROUP_ID, controller.getGroupId()); - assertEquals(DroolsController.NO_ARTIFACT_ID, controller.getArtifactId()); - assertEquals(DroolsController.NO_VERSION, controller.getVersion()); + assertEquals(DroolsControllerConstants.NO_GROUP_ID, controller.getGroupId()); + assertEquals(DroolsControllerConstants.NO_ARTIFACT_ID, controller.getArtifactId()); + assertEquals(DroolsControllerConstants.NO_VERSION, controller.getVersion()); } @Test public void inventory() { - List<DroolsController> controllers = DroolsController.factory.inventory(); + List<DroolsController> controllers = DroolsControllerConstants.getFactory().inventory(); assertNotNull(controllers); - + for (int i = 0; i < controllers.size(); i++) { if (!isNullController(controllers.get(i)) && !isActualController(controllers.get(i))) { fail("drools controller is not a null controller"); @@ -83,31 +83,31 @@ public class DroolsControllerFactoryTest { if (droolsController == null) { return false; } - - if (!DroolsController.NO_GROUP_ID.equals(droolsController.getGroupId())) { + + if (!DroolsControllerConstants.NO_GROUP_ID.equals(droolsController.getGroupId())) { return false; } - - if (!DroolsController.NO_ARTIFACT_ID.equals(droolsController.getArtifactId())) { + + if (!DroolsControllerConstants.NO_ARTIFACT_ID.equals(droolsController.getArtifactId())) { return false; } - return DroolsController.NO_VERSION.equals(droolsController.getVersion()); + return DroolsControllerConstants.NO_VERSION.equals(droolsController.getVersion()); } private boolean isActualController(DroolsController droolsController) { if (droolsController == null) { return false; } - + if (!"org.onap.policy.drools.test".equals(droolsController.getGroupId())) { return false; } - + if (!"protocolcoder".equals(droolsController.getArtifactId())) { return false; } - + return droolsController.getVersion() != null && droolsController.getVersion().substring(0, 1).matches("[0-9]"); } } diff --git a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController2Test.java b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController2Test.java index 20b79bde..7187ad1b 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController2Test.java +++ b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController2Test.java @@ -58,7 +58,9 @@ import org.onap.policy.common.utils.services.OrderedServiceImpl; import org.onap.policy.drools.core.PolicyContainer; import org.onap.policy.drools.core.PolicySession; import org.onap.policy.drools.features.DroolsControllerFeatureApi; +import org.onap.policy.drools.features.DroolsControllerFeatureApiConstants; import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants; import org.onap.policy.drools.protocol.coders.EventProtocolParams; import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration; @@ -887,8 +889,8 @@ public class MavenDroolsController2Test { } }; - assertSame(EventProtocolCoder.manager, drools.getCoderManager()); - assertSame(DroolsControllerFeatureApi.providers, drools.getDroolsProviders()); + assertSame(EventProtocolCoderConstants.getManager(), drools.getCoderManager()); + assertSame(DroolsControllerFeatureApiConstants.getProviders(), drools.getDroolsProviders()); } @Test diff --git a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/NullDroolsControllerTest.java b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/NullDroolsControllerTest.java index 4b0c438f..8515582d 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/NullDroolsControllerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/NullDroolsControllerTest.java @@ -24,6 +24,7 @@ import org.junit.Assert; import org.junit.Test; import org.onap.policy.common.utils.gson.GsonTestUtils; import org.onap.policy.drools.controller.DroolsController; +import org.onap.policy.drools.controller.DroolsControllerConstants; public class NullDroolsControllerTest { @@ -56,17 +57,17 @@ public class NullDroolsControllerTest { @Test public void getGroupId() { - Assert.assertEquals(new NullDroolsController().getGroupId(), DroolsController.NO_GROUP_ID); + Assert.assertEquals(new NullDroolsController().getGroupId(), DroolsControllerConstants.NO_GROUP_ID); } @Test public void getArtifactId() { - Assert.assertEquals(new NullDroolsController().getArtifactId(), DroolsController.NO_ARTIFACT_ID); + Assert.assertEquals(new NullDroolsController().getArtifactId(), DroolsControllerConstants.NO_ARTIFACT_ID); } @Test public void getVersion() { - Assert.assertEquals(new NullDroolsController().getVersion(), DroolsController.NO_VERSION); + Assert.assertEquals(new NullDroolsController().getVersion(), DroolsControllerConstants.NO_VERSION); } @Test diff --git a/policy-management/src/test/java/org/onap/policy/drools/persistence/SystemPersistenceTest.java b/policy-management/src/test/java/org/onap/policy/drools/persistence/SystemPersistenceTest.java index b2771944..8cd4ee6e 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/persistence/SystemPersistenceTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/persistence/SystemPersistenceTest.java @@ -37,7 +37,7 @@ import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; -import org.onap.policy.drools.properties.DroolsProperties; +import org.onap.policy.drools.properties.DroolsPropertyConstants; /** * (File) System Persistence Tests. @@ -103,24 +103,24 @@ public class SystemPersistenceTest { @Test public void test1NonDefaultConfigDir() { - SystemPersistence.manager.setConfigurationDir(OTHER_CONFIG_DIR); - assertEquals(OTHER_CONFIG_DIR, SystemPersistence.manager.getConfigurationPath().toString()); + SystemPersistenceConstants.getManager().setConfigurationDir(OTHER_CONFIG_DIR); + assertEquals(OTHER_CONFIG_DIR, SystemPersistenceConstants.getManager().getConfigurationPath().toString()); - SystemPersistence.manager.setConfigurationDir(null); - assertEquals(SystemPersistence.DEFAULT_CONFIGURATION_DIR, - SystemPersistence.manager.getConfigurationPath().toString()); + SystemPersistenceConstants.getManager().setConfigurationDir(null); + assertEquals(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR, + SystemPersistenceConstants.getManager().getConfigurationPath().toString()); - SystemPersistence.manager.setConfigurationDir(); - assertEquals(SystemPersistence.DEFAULT_CONFIGURATION_DIR, - SystemPersistence.manager.getConfigurationPath().toString()); + SystemPersistenceConstants.getManager().setConfigurationDir(); + assertEquals(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR, + SystemPersistenceConstants.getManager().getConfigurationPath().toString()); } @Test public void test2Engine_Environment_System() throws IOException { - SystemPersistence.manager.setConfigurationDir(OTHER_CONFIG_DIR); + SystemPersistenceConstants.getManager().setConfigurationDir(OTHER_CONFIG_DIR); final Path policyEnginePropsPath = - Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), FileSystemPersistence.PROPERTIES_FILE_ENGINE); final Properties engineProps = new Properties(); @@ -132,113 +132,114 @@ public class SystemPersistenceTest { } } - assertEquals(engineProps, SystemPersistence.manager.getEngineProperties()); + assertEquals(engineProps, SystemPersistenceConstants.getManager().getEngineProperties()); final Path environmentPropertiesPath = - Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), ENV_PROPS_FILE); + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), ENV_PROPS_FILE); if (Files.notExists(environmentPropertiesPath)) { Files.createFile(environmentPropertiesPath); } - assertNotNull(SystemPersistence.manager.getEnvironmentProperties(ENV_PROPS)); - assertTrue(SystemPersistence.manager.getEnvironmentProperties(ENV_PROPS).isEmpty()); - assertEquals(1, SystemPersistence.manager.getEnvironmentProperties().size()); - assertEquals(SystemPersistence.manager.getEnvironmentProperties(ENV_PROPS), - SystemPersistence.manager.getEnvironmentProperties().get(0)); + assertNotNull(SystemPersistenceConstants.getManager().getEnvironmentProperties(ENV_PROPS)); + assertTrue(SystemPersistenceConstants.getManager().getEnvironmentProperties(ENV_PROPS).isEmpty()); + assertEquals(1, SystemPersistenceConstants.getManager().getEnvironmentProperties().size()); + assertEquals(SystemPersistenceConstants.getManager().getEnvironmentProperties(ENV_PROPS), + SystemPersistenceConstants.getManager().getEnvironmentProperties().get(0)); Path systemPropertiesPath = - Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), SYSTEM_PROPS_FILE); + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), SYSTEM_PROPS_FILE); if (Files.notExists(systemPropertiesPath)) { Files.createFile(systemPropertiesPath); } - assertNotNull(SystemPersistence.manager.getSystemProperties(SYSTEM_PROPS)); - assertTrue(SystemPersistence.manager.getSystemProperties(SYSTEM_PROPS).isEmpty()); - assertEquals(1, SystemPersistence.manager.getSystemProperties().size()); - assertEquals(SystemPersistence.manager.getSystemProperties(SYSTEM_PROPS), - SystemPersistence.manager.getSystemProperties().get(0)); + assertNotNull(SystemPersistenceConstants.getManager().getSystemProperties(SYSTEM_PROPS)); + assertTrue(SystemPersistenceConstants.getManager().getSystemProperties(SYSTEM_PROPS).isEmpty()); + assertEquals(1, SystemPersistenceConstants.getManager().getSystemProperties().size()); + assertEquals(SystemPersistenceConstants.getManager().getSystemProperties(SYSTEM_PROPS), + SystemPersistenceConstants.getManager().getSystemProperties().get(0)); } @Test public void test3Topic() { - SystemPersistence.manager.setConfigurationDir(null); + SystemPersistenceConstants.getManager().setConfigurationDir(null); Path topicPath = Paths - .get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_TOPIC_FILE); + .get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), TEST_TOPIC_FILE); Path topicBakPath = Paths - .get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_TOPIC_FILE_BAK); + .get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), TEST_TOPIC_FILE_BAK); assertTrue(Files.notExists(topicPath)); assertTrue(Files.notExists(topicBakPath)); - SystemPersistence.manager.storeTopic(TEST_TOPIC_NAME, new Properties()); + SystemPersistenceConstants.getManager().storeTopic(TEST_TOPIC_NAME, new Properties()); assertTrue(Files.exists(topicPath)); - Properties properties = SystemPersistence.manager.getTopicProperties(TEST_TOPIC_NAME); + Properties properties = SystemPersistenceConstants.getManager().getTopicProperties(TEST_TOPIC_NAME); assertNotNull(properties); - List<Properties> topicPropsList = SystemPersistence.manager.getTopicProperties(); + List<Properties> topicPropsList = SystemPersistenceConstants.getManager().getTopicProperties(); assertEquals(1, topicPropsList.size()); - SystemPersistence.manager.backupTopic(TEST_TOPIC_NAME); + SystemPersistenceConstants.getManager().backupTopic(TEST_TOPIC_NAME); assertTrue(Files.exists(topicBakPath)); - SystemPersistence.manager.deleteTopic(TEST_TOPIC_NAME); + SystemPersistenceConstants.getManager().deleteTopic(TEST_TOPIC_NAME); assertTrue(Files.notExists(topicPath)); } @Test public void test4Controller() { - SystemPersistence.manager.setConfigurationDir(null); + SystemPersistenceConstants.getManager().setConfigurationDir(null); Path controllerPath = Paths - .get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE); + .get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), TEST_CONTROLLER_FILE); - Path controllerBakPath = Paths - .get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE_BAK); + Path controllerBakPath = Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), + TEST_CONTROLLER_FILE_BAK); assertTrue(Files.notExists(controllerPath)); assertTrue(Files.notExists(controllerBakPath)); - SystemPersistence.manager.storeController(TEST_CONTROLLER_NAME, new Properties()); + SystemPersistenceConstants.getManager().storeController(TEST_CONTROLLER_NAME, new Properties()); assertTrue(Files.exists(controllerPath)); - Properties properties = SystemPersistence.manager.getControllerProperties(TEST_CONTROLLER_NAME); + Properties properties = SystemPersistenceConstants.getManager().getControllerProperties(TEST_CONTROLLER_NAME); assertNotNull(properties); - List<Properties> controllerPropsList = SystemPersistence.manager.getControllerProperties(); + List<Properties> controllerPropsList = SystemPersistenceConstants.getManager().getControllerProperties(); assertEquals(1, controllerPropsList.size()); assertEquals(TEST_CONTROLLER_NAME, controllerPropsList - .get(0).getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME)); + .get(0).getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME)); - SystemPersistence.manager.backupController(TEST_CONTROLLER_NAME); + SystemPersistenceConstants.getManager().backupController(TEST_CONTROLLER_NAME); assertTrue(Files.exists(controllerBakPath)); - SystemPersistence.manager.deleteController(TEST_CONTROLLER_NAME); + SystemPersistenceConstants.getManager().deleteController(TEST_CONTROLLER_NAME); assertTrue(Files.notExists(controllerPath)); } /** * Clean up the working directories. - * + * * @throws IOException throws IO exception */ private static void cleanUpWorkingDirs() throws IOException { - SystemPersistence.manager.setConfigurationDir(null); + SystemPersistenceConstants.getManager().setConfigurationDir(null); - for (Properties properties : SystemPersistence.manager.getControllerProperties()) { - SystemPersistence.manager.deleteController(properties - .getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME)); + for (Properties properties : SystemPersistenceConstants.getManager().getControllerProperties()) { + SystemPersistenceConstants.getManager().deleteController(properties + .getProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME)); } - SystemPersistence.manager.deleteTopic(TEST_TOPIC_NAME); + SystemPersistenceConstants.getManager().deleteTopic(TEST_TOPIC_NAME); - final Path testControllerBakPath = Paths - .get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE_BAK); + final Path testControllerBakPath = + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), + TEST_CONTROLLER_FILE_BAK); final Path testTopicBakPath = Paths - .get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_TOPIC_FILE_BAK); + .get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), TEST_TOPIC_FILE_BAK); final Path policyEnginePath = Paths.get(OTHER_CONFIG_DIR, FileSystemPersistence.PROPERTIES_FILE_ENGINE); final Path environmentPath = Paths.get(OTHER_CONFIG_DIR, ENV_PROPS_FILE); diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java index db90bea7..6f34c2c1 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java @@ -83,18 +83,18 @@ public class EventProtocolCoderTest { TopicEndpointManager.getManager().addTopicSinks(noopSinkProperties); - EventProtocolCoder.manager.addEncoder( + EventProtocolCoderConstants.getManager().addEncoder( EventProtocolParams.builder().groupId(ENCODER_GROUP).artifactId(ENCODER_ARTIFACT) .topic(NOOP_TOPIC).eventClass(DroolsConfiguration.class.getName()) .protocolFilter(new JsonProtocolFilter()).customGsonCoder(null) .modelClassLoaderHash(DroolsConfiguration.class.getName().hashCode())); - final String json = EventProtocolCoder.manager.encode(NOOP_TOPIC, + final String json = EventProtocolCoderConstants.getManager().encode(NOOP_TOPIC, new DroolsConfiguration(ENCODER_GROUP, ENCODER_ARTIFACT, ENCODER_VERSION)); assertTrue(json.contains(ENCODER_GROUP)); assertTrue(json.contains(ENCODER_ARTIFACT)); - EventProtocolCoder.manager.removeEncoders(ENCODER_GROUP, ENCODER_ARTIFACT, NOOP_TOPIC); + EventProtocolCoderConstants.getManager().removeEncoders(ENCODER_GROUP, ENCODER_ARTIFACT, NOOP_TOPIC); } } diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java index 64661845..bd595725 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java @@ -34,9 +34,9 @@ import org.kie.api.builder.ReleaseId; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; -import org.onap.policy.drools.controller.DroolsController; +import org.onap.policy.drools.controller.DroolsControllerConstants; import org.onap.policy.drools.controller.internal.MavenDroolsControllerTest; -import org.onap.policy.drools.properties.DroolsProperties; +import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.protocol.coders.EventProtocolCoder.CoderFilters; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder; import org.onap.policy.drools.util.KieUtils; @@ -234,13 +234,13 @@ public class ProtocolCoderToolsetTest { final List<? extends TopicSink> noopTopics = TopicEndpointManager.getManager().addTopicSinks(sinkConfig); Properties droolsControllerConfig = new Properties(); - droolsControllerConfig.put(DroolsProperties.RULES_GROUPID, releaseId.getGroupId()); - droolsControllerConfig.put(DroolsProperties.RULES_ARTIFACTID, releaseId.getArtifactId()); - droolsControllerConfig.put(DroolsProperties.RULES_VERSION, releaseId.getVersion()); + droolsControllerConfig.put(DroolsPropertyConstants.RULES_GROUPID, releaseId.getGroupId()); + droolsControllerConfig.put(DroolsPropertyConstants.RULES_ARTIFACTID, releaseId.getArtifactId()); + droolsControllerConfig.put(DroolsPropertyConstants.RULES_VERSION, releaseId.getVersion()); droolsControllerConfig.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS + "." + JUNIT_PROTOCOL_CODER_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX, Triple.class.getName()); - DroolsController.factory.build(droolsControllerConfig, null, noopTopics); + DroolsControllerConstants.getFactory().build(droolsControllerConfig, null, noopTopics); } private JsonProtocolFilter createFilterSet() { diff --git a/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java b/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java index 88712a3b..173c1738 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java @@ -48,9 +48,9 @@ import org.junit.runners.MethodSorters; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.common.utils.network.NetworkUtil; -import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.system.PolicyController; -import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; +import org.onap.policy.drools.system.PolicyControllerConstants; +import org.onap.policy.drools.system.PolicyEngineConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -107,23 +107,23 @@ public class RestManagerTest { public static void setUp() throws IOException, InterruptedException { cleanUpWorkingDirs(); - SystemPersistence.manager.setConfigurationDir(null); + SystemPersistenceConstants.getManager().setConfigurationDir(null); /* override default port */ - final Properties engineProps = PolicyEngine.manager.defaultTelemetryConfig(); + final Properties engineProps = PolicyEngineConstants.getManager().defaultTelemetryConfig(); engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + PolicyEngine.TELEMETRY_SERVER_DEFAULT_NAME + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, - "" + DEFAULT_TELEMETRY_PORT); + + PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_NAME + + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "" + DEFAULT_TELEMETRY_PORT); engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + PolicyEngine.TELEMETRY_SERVER_DEFAULT_NAME + + PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_NAME + PolicyEndPointProperties.PROPERTY_HTTP_FILTER_CLASSES_SUFFIX, TestAafTelemetryAuthFilter.class.getName()); engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + PolicyEngine.TELEMETRY_SERVER_DEFAULT_NAME + + PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_NAME + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, TELEMETRY_USER); engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + PolicyEngine.TELEMETRY_SERVER_DEFAULT_NAME + + PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_NAME + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, TELEMETRY_PASSWORD); @@ -141,11 +141,11 @@ public class RestManagerTest { engineProps.put(DMAAP_SINK_MECHID_KEY, DMAAP_MECHID); engineProps.put(DMAAP_SINK_PASSWD_KEY, DMAAP_PASSWD); - PolicyEngine.manager.configure(engineProps); - PolicyEngine.manager.start(); + PolicyEngineConstants.getManager().configure(engineProps); + PolicyEngineConstants.getManager().start(); Properties controllerProps = new Properties(); - PolicyEngine.manager.createPolicyController(FOO_CONTROLLER, controllerProps); + PolicyEngineConstants.getManager().createPolicyController(FOO_CONTROLLER, controllerProps); // client = HttpClients.createDefault(); CredentialsProvider provider = new BasicCredentialsProvider(); @@ -173,9 +173,9 @@ public class RestManagerTest { @AfterClass public static void tearDown() throws IOException, InterruptedException { /* Shutdown managed resources */ - PolicyController.factory.shutdown(); + PolicyControllerConstants.getFactory().shutdown(); TopicEndpointManager.getManager().shutdown(); - PolicyEngine.manager.stop(); + PolicyEngineConstants.getManager().stop(); Thread.sleep(10000L); client.close(); cleanUpWorkingDirs(); @@ -441,7 +441,7 @@ public class RestManagerTest { assertEquals(200, response.getStatusLine().getStatusCode()); httpGet.releaseConnection(); - PolicyEngine.manager.setEnvironmentProperty("foo", "bar"); + PolicyEngineConstants.getManager().setEnvironmentProperty("foo", "bar"); httpGet = new HttpGet(HOST_URL + "/engine/environment/foo"); response = client.execute(httpGet); String responseBody = this.getResponseBody(response); @@ -962,10 +962,11 @@ public class RestManagerTest { } private static void cleanUpWorkingDirs() throws IOException { - final Path testControllerPath = - Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), FOO_CONTROLLER_FILE); + final Path testControllerPath = Paths.get( + SystemPersistenceConstants.getManager().getConfigurationPath().toString(), FOO_CONTROLLER_FILE); final Path testControllerBakPath = - Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), FOO_CONTROLLER_FILE_BAK); + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), + FOO_CONTROLLER_FILE_BAK); Files.deleteIfExists(testControllerPath); Files.deleteIfExists(testControllerBakPath); diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineManagerTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineManagerTest.java index c5fa3980..e9f0b48a 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineManagerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineManagerTest.java @@ -56,7 +56,7 @@ import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.features.PolicyControllerFeatureApi; import org.onap.policy.drools.features.PolicyEngineFeatureApi; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.DroolsProperties; +import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.protocol.coders.EventProtocolCoder; import org.onap.policy.drools.protocol.configuration.ControllerConfiguration; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; @@ -492,19 +492,19 @@ public class PolicyEngineManagerTest { // empty name in properties - same result setUp(); - properties.setProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME, ""); + properties.setProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, ""); assertEquals(controller, mgr.createPolicyController(MY_NAME, properties)); verify(contProv1).beforeCreate(MY_NAME, properties); // matching name in properties - same result setUp(); - properties.setProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME, MY_NAME); + properties.setProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, MY_NAME); assertEquals(controller, mgr.createPolicyController(MY_NAME, properties)); verify(contProv1).beforeCreate(MY_NAME, properties); // mismatching name in properties - nothing should happen besides exception setUp(); - properties.setProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME, "mistmatched-name"); + properties.setProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, "mistmatched-name"); assertThatIllegalStateException().isThrownBy(() -> mgr.createPolicyController(MY_NAME, properties)); verify(contProv1, never()).beforeCreate(MY_NAME, properties); diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineTest.java index d47c2183..df1f6cca 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/PolicyEngineTest.java @@ -39,9 +39,9 @@ import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicFactories; import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.common.utils.gson.GsonTestUtils; -import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.DroolsProperties; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.persistence.SystemPersistenceConstants; +import org.onap.policy.drools.properties.DroolsPropertyConstants; +import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants; import org.onap.policy.drools.protocol.coders.EventProtocolParams; import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; @@ -106,7 +106,8 @@ public class PolicyEngineTest { */ protected static void cleanUpWorkingDir() { final Path testControllerPath = - Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE); + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), + TEST_CONTROLLER_FILE); try { Files.deleteIfExists(testControllerPath); } catch (final Exception e) { @@ -114,7 +115,8 @@ public class PolicyEngineTest { } final Path testControllerBakPath = - Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE_BAK); + Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(), + TEST_CONTROLLER_FILE_BAK); try { Files.deleteIfExists(testControllerBakPath); } catch (final Exception e) { @@ -136,7 +138,7 @@ public class PolicyEngineTest { cleanUpWorkingDir(); /* ensure presence of config directory */ - final Path configDir = Paths.get(SystemPersistence.DEFAULT_CONFIGURATION_DIR); + final Path configDir = Paths.get(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR); if (Files.notExists(configDir)) { Files.createDirectories(configDir); } @@ -152,56 +154,57 @@ public class PolicyEngineTest { public void test100Configure() { logger.info("enter"); - final Properties engineProps = PolicyEngine.manager.defaultTelemetryConfig(); + final Properties engineProps = PolicyEngineConstants.getManager().defaultTelemetryConfig(); /* override default port */ engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + PolicyEngine.TELEMETRY_SERVER_DEFAULT_NAME + + PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_NAME + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "" + DEFAULT_TELEMETRY_PORT); - assertFalse(PolicyEngine.manager.isAlive()); - PolicyEngine.manager.configure(engineProps); - assertFalse(PolicyEngine.manager.isAlive()); + assertFalse(PolicyEngineConstants.getManager().isAlive()); + PolicyEngineConstants.getManager().configure(engineProps); + assertFalse(PolicyEngineConstants.getManager().isAlive()); - logger.info("engine {} has configuration {}", PolicyEngine.manager, engineProps); + logger.info("engine {} has configuration {}", PolicyEngineConstants.getManager(), engineProps); - gson.compareGson(PolicyEngine.manager, new File(PolicyEngineTest.class.getSimpleName() + "Config.json")); + gson.compareGson(PolicyEngineConstants.getManager(), + new File(PolicyEngineTest.class.getSimpleName() + "Config.json")); } @Test public void test200Start() { logger.info("enter"); - PolicyEngine.manager.start(); + PolicyEngineConstants.getManager().start(); - assertTrue(PolicyEngine.manager.isAlive()); - assertFalse(PolicyEngine.manager.isLocked()); - assertFalse(PolicyEngine.manager.getHttpServers().isEmpty()); - assertTrue(PolicyEngine.manager.getHttpServers().get(0).isAlive()); + assertTrue(PolicyEngineConstants.getManager().isAlive()); + assertFalse(PolicyEngineConstants.getManager().isLocked()); + assertFalse(PolicyEngineConstants.getManager().getHttpServers().isEmpty()); + assertTrue(PolicyEngineConstants.getManager().getHttpServers().get(0).isAlive()); } @Test public void test300Lock() { logger.info("enter"); - PolicyEngine.manager.lock(); + PolicyEngineConstants.getManager().lock(); - assertTrue(PolicyEngine.manager.isAlive()); - assertTrue(PolicyEngine.manager.isLocked()); - assertFalse(PolicyEngine.manager.getHttpServers().isEmpty()); - assertTrue(PolicyEngine.manager.getHttpServers().get(0).isAlive()); + assertTrue(PolicyEngineConstants.getManager().isAlive()); + assertTrue(PolicyEngineConstants.getManager().isLocked()); + assertFalse(PolicyEngineConstants.getManager().getHttpServers().isEmpty()); + assertTrue(PolicyEngineConstants.getManager().getHttpServers().get(0).isAlive()); } @Test public void test301Unlock() { logger.info("enter"); - PolicyEngine.manager.unlock(); + PolicyEngineConstants.getManager().unlock(); - assertTrue(PolicyEngine.manager.isAlive()); - assertFalse(PolicyEngine.manager.isLocked()); - assertFalse(PolicyEngine.manager.getHttpServers().isEmpty()); - assertTrue(PolicyEngine.manager.getHttpServers().get(0).isAlive()); + assertTrue(PolicyEngineConstants.getManager().isAlive()); + assertFalse(PolicyEngineConstants.getManager().isLocked()); + assertFalse(PolicyEngineConstants.getManager().getHttpServers().isEmpty()); + assertTrue(PolicyEngineConstants.getManager().getHttpServers().get(0).isAlive()); } @Test @@ -211,20 +214,20 @@ public class PolicyEngineTest { TopicEndpointManager.getManager().addTopicSinks(noopSinkProperties).get(0).start(); - EventProtocolCoder.manager.addEncoder( + EventProtocolCoderConstants.getManager().addEncoder( EventProtocolParams.builder().groupId(ENCODER_GROUP).artifactId(ENCODER_ARTIFACT) .topic(NOOP_TOPIC).eventClass(DroolsConfiguration.class.getName()) .protocolFilter(new JsonProtocolFilter()).customGsonCoder(null) .modelClassLoaderHash(DroolsConfiguration.class.getName().hashCode())); - assertTrue(PolicyEngine.manager.deliver(NOOP_TOPIC, + assertTrue(PolicyEngineConstants.getManager().deliver(NOOP_TOPIC, new DroolsConfiguration(ENCODER_GROUP, ENCODER_ARTIFACT, ENCODER_VERSION))); final TopicSink sink = NoopTopicFactories.getSinkFactory().get(NOOP_TOPIC); assertTrue(sink.getRecentEvents()[0].contains(ENCODER_GROUP)); assertTrue(sink.getRecentEvents()[0].contains(ENCODER_ARTIFACT)); - EventProtocolCoder.manager.removeEncoders(ENCODER_GROUP, ENCODER_ARTIFACT, NOOP_TOPIC); + EventProtocolCoderConstants.getManager().removeEncoders(ENCODER_GROUP, ENCODER_ARTIFACT, NOOP_TOPIC); } @Test @@ -232,19 +235,20 @@ public class PolicyEngineTest { logger.info("enter"); final Properties controllerProperties = new Properties(); - controllerProperties.put(DroolsProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME); - PolicyEngine.manager.createPolicyController(TEST_CONTROLLER_NAME, controllerProperties); + controllerProperties.put(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME); + PolicyEngineConstants.getManager().createPolicyController(TEST_CONTROLLER_NAME, controllerProperties); - assertTrue(PolicyController.factory.inventory().size() == 1); + assertTrue(PolicyControllerConstants.getFactory().inventory().size() == 1); - gson.compareGson(PolicyEngine.manager, new File(PolicyEngineTest.class.getSimpleName() + "Add.json")); + gson.compareGson(PolicyEngineConstants.getManager(), + new File(PolicyEngineTest.class.getSimpleName() + "Add.json")); } @Test public void test401ControllerVerify() { logger.info("enter"); - final PolicyController testController = PolicyController.factory.get(TEST_CONTROLLER_NAME); + final PolicyController testController = PolicyControllerConstants.getFactory().get(TEST_CONTROLLER_NAME); assertFalse(testController.isAlive()); assertFalse(testController.isLocked()); @@ -259,34 +263,34 @@ public class PolicyEngineTest { public void test500Deactivate() throws Exception { logger.info("enter"); - PolicyEngine.manager.deactivate(); + PolicyEngineConstants.getManager().deactivate(); - final PolicyController testController = PolicyController.factory.get(TEST_CONTROLLER_NAME); + final PolicyController testController = PolicyControllerConstants.getFactory().get(TEST_CONTROLLER_NAME); assertFalse(testController.isAlive()); assertTrue(testController.isLocked()); - assertTrue(PolicyEngine.manager.isLocked()); - assertTrue(PolicyEngine.manager.isAlive()); + assertTrue(PolicyEngineConstants.getManager().isLocked()); + assertTrue(PolicyEngineConstants.getManager().isAlive()); } @Test public void test501Activate() throws Exception { logger.info("enter"); - PolicyEngine.manager.activate(); + PolicyEngineConstants.getManager().activate(); - final PolicyController testController = PolicyController.factory.get(TEST_CONTROLLER_NAME); + final PolicyController testController = PolicyControllerConstants.getFactory().get(TEST_CONTROLLER_NAME); assertTrue(testController.isAlive()); assertFalse(testController.isLocked()); - assertFalse(PolicyEngine.manager.isLocked()); - assertTrue(PolicyEngine.manager.isAlive()); + assertFalse(PolicyEngineConstants.getManager().isLocked()); + assertTrue(PolicyEngineConstants.getManager().isAlive()); } @Test public void test900ControllerRemove() throws Exception { logger.info("enter"); - PolicyEngine.manager.removePolicyController(TEST_CONTROLLER_NAME); - assertTrue(PolicyController.factory.inventory().isEmpty()); + PolicyEngineConstants.getManager().removePolicyController(TEST_CONTROLLER_NAME); + assertTrue(PolicyControllerConstants.getFactory().inventory().isEmpty()); } @Test @@ -294,11 +298,11 @@ public class PolicyEngineTest { logger.info("enter"); /* Shutdown managed resources */ - PolicyController.factory.shutdown(); + PolicyControllerConstants.getFactory().shutdown(); TopicEndpointManager.getManager().shutdown(); - PolicyEngine.manager.stop(); + PolicyEngineConstants.getManager().stop(); Thread.sleep(10000L); - assertFalse(PolicyEngine.manager.isAlive()); + assertFalse(PolicyEngineConstants.getManager().isAlive()); } } diff --git a/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransaction.java b/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransaction.java index e3b2f8a8..d56e63e6 100644 --- a/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransaction.java +++ b/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransaction.java @@ -20,7 +20,6 @@ package org.onap.policy.drools.utils.logging; import java.time.Instant; -import org.onap.policy.common.utils.network.NetworkUtil; /** * MDC Transaction Utility Class. @@ -49,156 +48,6 @@ import org.onap.policy.common.utils.network.NetworkUtil; * <p>https://wiki.onap.org/pages/viewpage.action?pageId=20087036 */ public interface MdcTransaction { - /* - * The fields must match the naming given at - * https://wiki.onap.org/pages/viewpage.action?pageId=20087036 - */ - - /** - * End to end transaction ID. Subtransactions will inherit this value from the transaction. - */ - String REQUEST_ID = "RequestID"; - - /** - * Invocation ID, ie. SubTransaction ID. - */ - String INVOCATION_ID = "InvocationID"; - - /** - * Service Name. Both transactions and subtransactions will have its own copy. - */ - String SERVICE_NAME = "ServiceName"; - - /** - * Partner Name Subtransactions will inherit this value from the transaction. - */ - String PARTNER_NAME = "PartnerName"; - - /** - * Start Timestamp. Both transactions and subtransactions will have its own copy. - */ - String BEGIN_TIMESTAMP = "BeginTimestamp"; - - /** - * End Timestamp. Both transactions and subtransactions will have its own copy. - */ - String END_TIMESTAMP = "EndTimestamp"; - - /** - * Elapsed Time. Both transactions and subtransactions will have its own copy. - */ - String ELAPSED_TIME = "ElapsedTime"; - - /** - * Elapsed Time. Both transactions and subtransactions will have its own copy. - */ - String SERVICE_INSTANCE_ID = "ServiceInstanceID"; - - /** - * Virtual Server Name. Subtransactions will inherit this value from the transaction. - */ - String VIRTUAL_SERVER_NAME = "VirtualServerName"; - - /** - * Status Code Both transactions and subtransactions will have its own copy. - */ - String STATUS_CODE = "StatusCode"; - - /** - * Response Code Both transactions and subtransactions will have its own copy. - */ - String RESPONSE_CODE = "ResponseCode"; - - /** - * Response Description Both transactions and subtransactions will have its own copy. - */ - String RESPONSE_DESCRIPTION = "ResponseDescription"; - - /** - * Instance UUID Both transactions and subtransactions will have its own copy. - */ - String INSTANCE_UUID = "InstanceUUID"; - - /** - * Severity Both transactions and subtransactions will have its own copy. - */ - String SEVERITY = "Severity"; - - /** - * Target Entity Both transactions and subtransactions will have its own copy. - */ - String TARGET_ENTITY = "TargetEntity"; - - /** - * Target Service Name Both transactions and subtransactions will have its own copy. - */ - String TARGET_SERVICE_NAME = "TargetServiceName"; - - /** - * Server Subtransactions inherit this value. if (this.getSources().size() == 1) - * this.getSources().get(0).getTopic(); - */ - String SERVER = "Server"; - - /** - * Server IP Address Subtransactions inherit this value. - */ - String SERVER_IP_ADDRESS = "ServerIpAddress"; - - /** - * Server FQDN Subtransactions inherit this value. - */ - String SERVER_FQDN = "ServerFQDN"; - - /** - * Client IP Address Both transactions and subtransactions will have its own copy. - */ - String CLIENT_IP_ADDRESS = "ClientIPAddress"; - - /** - * Process Key Both transactions and subtransactions will have its own copy. - */ - String PROCESS_KEY = "ProcessKey"; - - /** - * Remote Host Both transactions and subtransactions will have its own copy. - */ - String REMOTE_HOST = "RemoteHost"; - - /** - * Alert Severity Both transactions and subtransactions will have its own copy. - */ - String ALERT_SEVERITY = "AlertSeverity"; - - /** - * Target Virtual Entity Both transactions and subtransactions will have its own copy. - */ - String TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity"; - - /** - * Default Service Name. - */ - String DEFAULT_SERVICE_NAME = "PDP-D"; - - /** - * Default Host Name. - */ - String DEFAULT_HOSTNAME = NetworkUtil.getHostname(); - - /** - * Default Host IP. - */ - String DEFAULT_HOSTIP = NetworkUtil.getHostIp(); - - /** - * Status Code Complete. - */ - String STATUS_CODE_COMPLETE = "COMPLETE"; - - /** - * Status Code Error. - */ - String STATUS_CODE_FAILURE = "ERROR"; /** * reset subtransaction data. diff --git a/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransactionConstants.java b/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransactionConstants.java new file mode 100644 index 00000000..ba335958 --- /dev/null +++ b/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransactionConstants.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * policy-utils + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.policy.drools.utils.logging; + +import org.onap.policy.common.utils.network.NetworkUtil; + +public class MdcTransactionConstants { + /* + * The fields must match the naming given at + * https://wiki.onap.org/pages/viewpage.action?pageId=20087036 + */ + + /** + * End to end transaction ID. Subtransactions will inherit this value from the transaction. + */ + public static final String REQUEST_ID = "RequestID"; + + /** + * Invocation ID, ie. SubTransaction ID. + */ + public static final String INVOCATION_ID = "InvocationID"; + + /** + * Service Name. Both transactions and subtransactions will have its own copy. + */ + public static final String SERVICE_NAME = "ServiceName"; + + /** + * Partner Name Subtransactions will inherit this value from the transaction. + */ + public static final String PARTNER_NAME = "PartnerName"; + + /** + * Start Timestamp. Both transactions and subtransactions will have its own copy. + */ + public static final String BEGIN_TIMESTAMP = "BeginTimestamp"; + + /** + * End Timestamp. Both transactions and subtransactions will have its own copy. + */ + public static final String END_TIMESTAMP = "EndTimestamp"; + + /** + * Elapsed Time. Both transactions and subtransactions will have its own copy. + */ + public static final String ELAPSED_TIME = "ElapsedTime"; + + /** + * Elapsed Time. Both transactions and subtransactions will have its own copy. + */ + public static final String SERVICE_INSTANCE_ID = "ServiceInstanceID"; + + /** + * Virtual Server Name. Subtransactions will inherit this value from the transaction. + */ + public static final String VIRTUAL_SERVER_NAME = "VirtualServerName"; + + /** + * Status Code Both transactions and subtransactions will have its own copy. + */ + public static final String STATUS_CODE = "StatusCode"; + + /** + * Response Code Both transactions and subtransactions will have its own copy. + */ + public static final String RESPONSE_CODE = "ResponseCode"; + + /** + * Response Description Both transactions and subtransactions will have its own copy. + */ + public static final String RESPONSE_DESCRIPTION = "ResponseDescription"; + + /** + * Instance UUID Both transactions and subtransactions will have its own copy. + */ + public static final String INSTANCE_UUID = "InstanceUUID"; + + /** + * Severity Both transactions and subtransactions will have its own copy. + */ + public static final String SEVERITY = "Severity"; + + /** + * Target Entity Both transactions and subtransactions will have its own copy. + */ + public static final String TARGET_ENTITY = "TargetEntity"; + + /** + * Target Service Name Both transactions and subtransactions will have its own copy. + */ + public static final String TARGET_SERVICE_NAME = "TargetServiceName"; + + /** + * Server Subtransactions inherit this value. if (this.getSources().size() == 1) + * this.getSources().get(0).getTopic(); + */ + public static final String SERVER = "Server"; + + /** + * Server IP Address Subtransactions inherit this value. + */ + public static final String SERVER_IP_ADDRESS = "ServerIpAddress"; + + /** + * Server FQDN Subtransactions inherit this value. + */ + public static final String SERVER_FQDN = "ServerFQDN"; + + /** + * Client IP Address Both transactions and subtransactions will have its own copy. + */ + public static final String CLIENT_IP_ADDRESS = "ClientIPAddress"; + + /** + * Process Key Both transactions and subtransactions will have its own copy. + */ + public static final String PROCESS_KEY = "ProcessKey"; + + /** + * Remote Host Both transactions and subtransactions will have its own copy. + */ + public static final String REMOTE_HOST = "RemoteHost"; + + /** + * Alert Severity Both transactions and subtransactions will have its own copy. + */ + public static final String ALERT_SEVERITY = "AlertSeverity"; + + /** + * Target Virtual Entity Both transactions and subtransactions will have its own copy. + */ + public static final String TARGET_VIRTUAL_ENTITY = "TargetVirtualEntity"; + + /** + * Default Service Name. + */ + public static final String DEFAULT_SERVICE_NAME = "PDP-D"; + + /** + * Default Host Name. + */ + public static final String DEFAULT_HOSTNAME = NetworkUtil.getHostname(); + + /** + * Default Host IP. + */ + public static final String DEFAULT_HOSTIP = NetworkUtil.getHostIp(); + + /** + * Status Code Complete. + */ + public static final String STATUS_CODE_COMPLETE = "COMPLETE"; + + /** + * Status Code Error. + */ + public static final String STATUS_CODE_FAILURE = "ERROR"; + + + private MdcTransactionConstants() { + // do nothing + } +} diff --git a/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransactionImpl.java b/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransactionImpl.java index 7289cd7a..f10343e2 100644 --- a/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransactionImpl.java +++ b/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MdcTransactionImpl.java @@ -20,6 +20,36 @@ package org.onap.policy.drools.utils.logging; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.ALERT_SEVERITY; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.BEGIN_TIMESTAMP; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.CLIENT_IP_ADDRESS; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.DEFAULT_HOSTIP; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.DEFAULT_HOSTNAME; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.DEFAULT_SERVICE_NAME; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.ELAPSED_TIME; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.END_TIMESTAMP; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.INSTANCE_UUID; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.INVOCATION_ID; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.PARTNER_NAME; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.PROCESS_KEY; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.REMOTE_HOST; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.REQUEST_ID; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.RESPONSE_CODE; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.RESPONSE_DESCRIPTION; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.SERVER; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.SERVER_FQDN; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.SERVER_IP_ADDRESS; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.SERVICE_INSTANCE_ID; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.SERVICE_NAME; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.SEVERITY; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.STATUS_CODE; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.STATUS_CODE_COMPLETE; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.STATUS_CODE_FAILURE; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.TARGET_ENTITY; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.TARGET_SERVICE_NAME; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.TARGET_VIRTUAL_ENTITY; +import static org.onap.policy.drools.utils.logging.MdcTransactionConstants.VIRTUAL_SERVER_NAME; + import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; @@ -46,7 +76,7 @@ class MdcTransactionImpl implements MdcTransaction { private String invocationId; private String virtualServerName; - private String server; + private String serverName; private String serverIpAddress; private String serverFqdn; @@ -63,7 +93,7 @@ class MdcTransactionImpl implements MdcTransaction { private String statusCode; private String responseCode; private String responseDescription; - private String severity; + private String theSeverity; private String alertSeverity; private String targetEntity; @@ -207,8 +237,8 @@ class MdcTransactionImpl implements MdcTransaction { MDC.put(VIRTUAL_SERVER_NAME, this.virtualServerName); } - if (this.server != null) { - MDC.put(SERVER, this.server); + if (this.serverName != null) { + MDC.put(SERVER, this.serverName); } if (this.serverIpAddress != null) { @@ -267,8 +297,8 @@ class MdcTransactionImpl implements MdcTransaction { MDC.put(RESPONSE_DESCRIPTION, this.responseDescription); } - if (this.severity != null) { - MDC.put(SEVERITY, this.severity); + if (this.theSeverity != null) { + MDC.put(SEVERITY, this.theSeverity); } if (this.alertSeverity != null) { @@ -365,7 +395,7 @@ class MdcTransactionImpl implements MdcTransaction { @Override public String getServer() { - return this.server; + return this.serverName; } @Override @@ -486,7 +516,7 @@ class MdcTransactionImpl implements MdcTransaction { @Override public MdcTransaction setSeverity(String severity) { - this.severity = severity; + this.theSeverity = severity; return this; } @@ -535,7 +565,7 @@ class MdcTransactionImpl implements MdcTransaction { @Override public String getSeverity() { - return severity; + return theSeverity; } @Override @@ -587,12 +617,12 @@ class MdcTransactionImpl implements MdcTransaction { @Override public MdcTransaction setServer(String server) { if (server == null || server.isEmpty()) { - this.server = DEFAULT_HOSTNAME; + this.serverName = DEFAULT_HOSTNAME; } else { - this.server = server; + this.serverName = server; } - MDC.put(SERVER, this.server); + MDC.put(SERVER, this.serverName); return this; } @@ -669,7 +699,7 @@ class MdcTransactionImpl implements MdcTransaction { sb.append(", partner='").append(partner).append('\''); sb.append(", invocationId='").append(invocationId).append('\''); sb.append(", virtualServerName='").append(virtualServerName).append('\''); - sb.append(", server='").append(server).append('\''); + sb.append(", server='").append(serverName).append('\''); sb.append(", serverIpAddress='").append(serverIpAddress).append('\''); sb.append(", serverFqdn='").append(serverFqdn).append('\''); sb.append(", serviceName='").append(serviceName).append('\''); @@ -682,7 +712,7 @@ class MdcTransactionImpl implements MdcTransaction { sb.append(", statusCode='").append(statusCode).append('\''); sb.append(", responseCode='").append(responseCode).append('\''); sb.append(", responseDescription='").append(responseDescription).append('\''); - sb.append(", severity='").append(severity).append('\''); + sb.append(", severity='").append(theSeverity).append('\''); sb.append(", alertSeverity='").append(alertSeverity).append('\''); sb.append(", targetEntity='").append(targetEntity).append('\''); sb.append(", targetServiceName='").append(targetServiceName).append('\''); diff --git a/policy-utils/src/test/java/org/onap/policy/drools/utils/logging/MdcTransactionTest.java b/policy-utils/src/test/java/org/onap/policy/drools/utils/logging/MdcTransactionTest.java index a552be46..9c0cf968 100644 --- a/policy-utils/src/test/java/org/onap/policy/drools/utils/logging/MdcTransactionTest.java +++ b/policy-utils/src/test/java/org/onap/policy/drools/utils/logging/MdcTransactionTest.java @@ -47,39 +47,39 @@ public class MdcTransactionTest { assertNullSubTransactionFields(trans); - assertNotNull(MDC.get(MdcTransaction.REQUEST_ID)); - assertNotNull(MDC.get(MdcTransaction.PARTNER_NAME)); - assertNotNull(MDC.get(MdcTransaction.VIRTUAL_SERVER_NAME)); - assertNotNull(MDC.get(MdcTransaction.SERVER)); - assertNotNull(MDC.get(MdcTransaction.SERVER_IP_ADDRESS)); - assertNotNull(MDC.get(MdcTransaction.SERVER_FQDN)); - assertNotNull(MDC.get(MdcTransaction.SERVICE_NAME)); - - assertNull(MDC.get(MdcTransaction.INVOCATION_ID)); - assertNull(MDC.get(MdcTransaction.BEGIN_TIMESTAMP)); - assertNull(MDC.get(MdcTransaction.END_TIMESTAMP)); - assertNull(MDC.get(MdcTransaction.ELAPSED_TIME)); - assertNull(MDC.get(MdcTransaction.SERVICE_INSTANCE_ID)); - assertNull(MDC.get(MdcTransaction.INSTANCE_UUID)); - assertNull(MDC.get(MdcTransaction.PROCESS_KEY)); - assertNull(MDC.get(MdcTransaction.STATUS_CODE)); - assertNull(MDC.get(MdcTransaction.RESPONSE_CODE)); - assertNull(MDC.get(MdcTransaction.RESPONSE_DESCRIPTION)); - assertNull(MDC.get(MdcTransaction.SEVERITY)); - assertNull(MDC.get(MdcTransaction.ALERT_SEVERITY)); - assertNull(MDC.get(MdcTransaction.TARGET_ENTITY)); - assertNull(MDC.get(MdcTransaction.TARGET_SERVICE_NAME)); - assertNull(MDC.get(MdcTransaction.TARGET_VIRTUAL_ENTITY)); - assertNull(MDC.get(MdcTransaction.CLIENT_IP_ADDRESS)); - assertNull(MDC.get(MdcTransaction.REMOTE_HOST)); - - assertEquals(trans.getRequestId(), MDC.get(MdcTransaction.REQUEST_ID)); - assertEquals(trans.getPartner(), MDC.get(MdcTransaction.PARTNER_NAME)); - assertEquals(trans.getVirtualServerName(), MDC.get(MdcTransaction.VIRTUAL_SERVER_NAME)); - assertEquals(trans.getServer(), MDC.get(MdcTransaction.SERVER)); - assertEquals(trans.getServerIpAddress(), MDC.get(MdcTransaction.SERVER_IP_ADDRESS)); - assertEquals(trans.getServerFqdn(), MDC.get(MdcTransaction.SERVER_FQDN)); - assertEquals(trans.getServiceName(), MDC.get(MdcTransaction.SERVICE_NAME)); + assertNotNull(MDC.get(MdcTransactionConstants.REQUEST_ID)); + assertNotNull(MDC.get(MdcTransactionConstants.PARTNER_NAME)); + assertNotNull(MDC.get(MdcTransactionConstants.VIRTUAL_SERVER_NAME)); + assertNotNull(MDC.get(MdcTransactionConstants.SERVER)); + assertNotNull(MDC.get(MdcTransactionConstants.SERVER_IP_ADDRESS)); + assertNotNull(MDC.get(MdcTransactionConstants.SERVER_FQDN)); + assertNotNull(MDC.get(MdcTransactionConstants.SERVICE_NAME)); + + assertNull(MDC.get(MdcTransactionConstants.INVOCATION_ID)); + assertNull(MDC.get(MdcTransactionConstants.BEGIN_TIMESTAMP)); + assertNull(MDC.get(MdcTransactionConstants.END_TIMESTAMP)); + assertNull(MDC.get(MdcTransactionConstants.ELAPSED_TIME)); + assertNull(MDC.get(MdcTransactionConstants.SERVICE_INSTANCE_ID)); + assertNull(MDC.get(MdcTransactionConstants.INSTANCE_UUID)); + assertNull(MDC.get(MdcTransactionConstants.PROCESS_KEY)); + assertNull(MDC.get(MdcTransactionConstants.STATUS_CODE)); + assertNull(MDC.get(MdcTransactionConstants.RESPONSE_CODE)); + assertNull(MDC.get(MdcTransactionConstants.RESPONSE_DESCRIPTION)); + assertNull(MDC.get(MdcTransactionConstants.SEVERITY)); + assertNull(MDC.get(MdcTransactionConstants.ALERT_SEVERITY)); + assertNull(MDC.get(MdcTransactionConstants.TARGET_ENTITY)); + assertNull(MDC.get(MdcTransactionConstants.TARGET_SERVICE_NAME)); + assertNull(MDC.get(MdcTransactionConstants.TARGET_VIRTUAL_ENTITY)); + assertNull(MDC.get(MdcTransactionConstants.CLIENT_IP_ADDRESS)); + assertNull(MDC.get(MdcTransactionConstants.REMOTE_HOST)); + + assertEquals(trans.getRequestId(), MDC.get(MdcTransactionConstants.REQUEST_ID)); + assertEquals(trans.getPartner(), MDC.get(MdcTransactionConstants.PARTNER_NAME)); + assertEquals(trans.getVirtualServerName(), MDC.get(MdcTransactionConstants.VIRTUAL_SERVER_NAME)); + assertEquals(trans.getServer(), MDC.get(MdcTransactionConstants.SERVER)); + assertEquals(trans.getServerIpAddress(), MDC.get(MdcTransactionConstants.SERVER_IP_ADDRESS)); + assertEquals(trans.getServerFqdn(), MDC.get(MdcTransactionConstants.SERVER_FQDN)); + assertEquals(trans.getServiceName(), MDC.get(MdcTransactionConstants.SERVICE_NAME)); } private void assertNullSubTransactionFields(MdcTransaction trans) { @@ -105,20 +105,20 @@ public class MdcTransactionTest { } protected void assertTransactionFields(MdcTransaction trans) { - assertEquals(trans.getRequestId(), MDC.get(MdcTransaction.REQUEST_ID)); - assertEquals(trans.getPartner(), MDC.get(MdcTransaction.PARTNER_NAME)); - assertEquals(trans.getVirtualServerName(), MDC.get(MdcTransaction.VIRTUAL_SERVER_NAME)); - assertEquals(trans.getServer(), MDC.get(MdcTransaction.SERVER)); - assertEquals(trans.getServerIpAddress(), MDC.get(MdcTransaction.SERVER_IP_ADDRESS)); - assertEquals(trans.getServerFqdn(), MDC.get(MdcTransaction.SERVER_FQDN)); - assertEquals(trans.getServiceName(), MDC.get(MdcTransaction.SERVICE_NAME)); + assertEquals(trans.getRequestId(), MDC.get(MdcTransactionConstants.REQUEST_ID)); + assertEquals(trans.getPartner(), MDC.get(MdcTransactionConstants.PARTNER_NAME)); + assertEquals(trans.getVirtualServerName(), MDC.get(MdcTransactionConstants.VIRTUAL_SERVER_NAME)); + assertEquals(trans.getServer(), MDC.get(MdcTransactionConstants.SERVER)); + assertEquals(trans.getServerIpAddress(), MDC.get(MdcTransactionConstants.SERVER_IP_ADDRESS)); + assertEquals(trans.getServerFqdn(), MDC.get(MdcTransactionConstants.SERVER_FQDN)); + assertEquals(trans.getServiceName(), MDC.get(MdcTransactionConstants.SERVICE_NAME)); } @Test public void flush() { MdcTransaction trans = - MdcTransaction.newTransaction() + MdcTransaction.newTransaction() .setRequestId(null) .setInvocationId(null) .setPartner(null) @@ -146,43 +146,43 @@ public class MdcTransactionTest { assertTransactionFields(trans); - assertNotNull(MDC.get(MdcTransaction.INVOCATION_ID)); - assertNotNull(MDC.get(MdcTransaction.BEGIN_TIMESTAMP)); - assertNotNull(MDC.get(MdcTransaction.END_TIMESTAMP)); - assertNotNull(MDC.get(MdcTransaction.ELAPSED_TIME)); - assertNotNull(MDC.get(MdcTransaction.SERVICE_INSTANCE_ID)); - assertNotNull(MDC.get(MdcTransaction.INSTANCE_UUID)); - assertNotNull(MDC.get(MdcTransaction.PROCESS_KEY)); - assertNotNull(MDC.get(MdcTransaction.STATUS_CODE)); - assertNotNull(MDC.get(MdcTransaction.RESPONSE_CODE)); - assertNotNull(MDC.get(MdcTransaction.RESPONSE_DESCRIPTION)); - assertNotNull(MDC.get(MdcTransaction.SEVERITY)); - assertNotNull(MDC.get(MdcTransaction.ALERT_SEVERITY)); - assertNotNull(MDC.get(MdcTransaction.TARGET_ENTITY)); - assertNotNull(MDC.get(MdcTransaction.TARGET_SERVICE_NAME)); - assertNotNull(MDC.get(MdcTransaction.TARGET_VIRTUAL_ENTITY)); - assertNotNull(MDC.get(MdcTransaction.CLIENT_IP_ADDRESS)); - assertNotNull(MDC.get(MdcTransaction.REMOTE_HOST)); - - assertEquals(trans.getInvocationId(), MDC.get(MdcTransaction.INVOCATION_ID)); - assertEquals(trans.timestamp(trans.getStartTime()), MDC.get(MdcTransaction.BEGIN_TIMESTAMP)); - assertEquals(trans.timestamp(trans.getEndTime()), MDC.get(MdcTransaction.END_TIMESTAMP)); - assertNotEquals(trans.getElapsedTime(), MDC.get(MdcTransaction.ELAPSED_TIME)); + assertNotNull(MDC.get(MdcTransactionConstants.INVOCATION_ID)); + assertNotNull(MDC.get(MdcTransactionConstants.BEGIN_TIMESTAMP)); + assertNotNull(MDC.get(MdcTransactionConstants.END_TIMESTAMP)); + assertNotNull(MDC.get(MdcTransactionConstants.ELAPSED_TIME)); + assertNotNull(MDC.get(MdcTransactionConstants.SERVICE_INSTANCE_ID)); + assertNotNull(MDC.get(MdcTransactionConstants.INSTANCE_UUID)); + assertNotNull(MDC.get(MdcTransactionConstants.PROCESS_KEY)); + assertNotNull(MDC.get(MdcTransactionConstants.STATUS_CODE)); + assertNotNull(MDC.get(MdcTransactionConstants.RESPONSE_CODE)); + assertNotNull(MDC.get(MdcTransactionConstants.RESPONSE_DESCRIPTION)); + assertNotNull(MDC.get(MdcTransactionConstants.SEVERITY)); + assertNotNull(MDC.get(MdcTransactionConstants.ALERT_SEVERITY)); + assertNotNull(MDC.get(MdcTransactionConstants.TARGET_ENTITY)); + assertNotNull(MDC.get(MdcTransactionConstants.TARGET_SERVICE_NAME)); + assertNotNull(MDC.get(MdcTransactionConstants.TARGET_VIRTUAL_ENTITY)); + assertNotNull(MDC.get(MdcTransactionConstants.CLIENT_IP_ADDRESS)); + assertNotNull(MDC.get(MdcTransactionConstants.REMOTE_HOST)); + + assertEquals(trans.getInvocationId(), MDC.get(MdcTransactionConstants.INVOCATION_ID)); + assertEquals(trans.timestamp(trans.getStartTime()), MDC.get(MdcTransactionConstants.BEGIN_TIMESTAMP)); + assertEquals(trans.timestamp(trans.getEndTime()), MDC.get(MdcTransactionConstants.END_TIMESTAMP)); + assertNotEquals(trans.getElapsedTime(), MDC.get(MdcTransactionConstants.ELAPSED_TIME)); assertEquals(String.valueOf(Duration.between(trans.getStartTime(), trans.getEndTime()).toMillis()), - MDC.get(MdcTransaction.ELAPSED_TIME)); - assertEquals(trans.getServiceInstanceId(), MDC.get(MdcTransaction.SERVICE_INSTANCE_ID)); - assertEquals(trans.getInstanceUuid(), MDC.get(MdcTransaction.INSTANCE_UUID)); - assertEquals(trans.getProcessKey(),MDC.get(MdcTransaction.PROCESS_KEY)); - assertEquals(trans.getStatusCode(), MDC.get(MdcTransaction.STATUS_CODE)); - assertEquals(trans.getResponseCode(), MDC.get(MdcTransaction.RESPONSE_CODE)); - assertEquals(trans.getResponseDescription(), MDC.get(MdcTransaction.RESPONSE_DESCRIPTION)); - assertEquals(trans.getSeverity(), MDC.get(MdcTransaction.SEVERITY)); - assertEquals(trans.getAlertSeverity(), MDC.get(MdcTransaction.ALERT_SEVERITY)); - assertEquals(trans.getTargetEntity(), MDC.get(MdcTransaction.TARGET_ENTITY)); - assertEquals(trans.getTargetServiceName(), MDC.get(MdcTransaction.TARGET_SERVICE_NAME)); - assertEquals(trans.getTargetVirtualEntity(), MDC.get(MdcTransaction.TARGET_VIRTUAL_ENTITY)); - assertEquals(trans.getClientIpAddress(), MDC.get(MdcTransaction.CLIENT_IP_ADDRESS)); - assertEquals(trans.getRemoteHost(), MDC.get(MdcTransaction.REMOTE_HOST)); + MDC.get(MdcTransactionConstants.ELAPSED_TIME)); + assertEquals(trans.getServiceInstanceId(), MDC.get(MdcTransactionConstants.SERVICE_INSTANCE_ID)); + assertEquals(trans.getInstanceUuid(), MDC.get(MdcTransactionConstants.INSTANCE_UUID)); + assertEquals(trans.getProcessKey(),MDC.get(MdcTransactionConstants.PROCESS_KEY)); + assertEquals(trans.getStatusCode(), MDC.get(MdcTransactionConstants.STATUS_CODE)); + assertEquals(trans.getResponseCode(), MDC.get(MdcTransactionConstants.RESPONSE_CODE)); + assertEquals(trans.getResponseDescription(), MDC.get(MdcTransactionConstants.RESPONSE_DESCRIPTION)); + assertEquals(trans.getSeverity(), MDC.get(MdcTransactionConstants.SEVERITY)); + assertEquals(trans.getAlertSeverity(), MDC.get(MdcTransactionConstants.ALERT_SEVERITY)); + assertEquals(trans.getTargetEntity(), MDC.get(MdcTransactionConstants.TARGET_ENTITY)); + assertEquals(trans.getTargetServiceName(), MDC.get(MdcTransactionConstants.TARGET_SERVICE_NAME)); + assertEquals(trans.getTargetVirtualEntity(), MDC.get(MdcTransactionConstants.TARGET_VIRTUAL_ENTITY)); + assertEquals(trans.getClientIpAddress(), MDC.get(MdcTransactionConstants.CLIENT_IP_ADDRESS)); + assertEquals(trans.getRemoteHost(), MDC.get(MdcTransactionConstants.REMOTE_HOST)); assertEquals("service-instance-id", trans.getServiceInstanceId()); assertEquals("process-key", trans.getProcessKey()); |