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
* 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
--- /dev/null
+/*-
+ * ============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
+ }
+}
<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>
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
*/
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
--- /dev/null
+/*-
+ * ============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
+ }
+}
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;
// 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());
@Override
public boolean afterStart(PolicyEngine engine) {
// ASSERTION: engine == PolicyEngine.manager
- PolicyEngine.manager.lock();
+ PolicyEngineConstants.getManager().lock();
return false;
}
} else {
siteName = siteName.trim();
}
- myPdp.setSiteName(siteName);
+ myPdp.setSite(siteName);
if (electionHandler == null) {
electionHandler = new DroolsPdpsElectionHandler(conn,myPdp);
}
* ============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.
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);
}
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
@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;
}
@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);
}
}
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;
//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);
}
}
}
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());
}
}
}
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;
//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());
}
}
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");
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()) {
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());
}
}
}
}
if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0) {
mostRecentPrimary = pdp;
- logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId());
+ logger.debug(RUN_PRIMARY_MSG, mostRecentPrimary.getPdpId());
}
}
} else {
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());
}
}
}
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;
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 = {}"
} 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");
}
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;
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;
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()) {
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) {
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
* 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;
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
droolsPdpEntity.setDesignated(pdp.isDesignated());
droolsPdpEntity.setPriority(pdp.getPriority());
droolsPdpEntity.setUpdatedDate(pdp.getUpdatedDate());
- droolsPdpEntity.setSiteName(pdp.getSiteName());
+ droolsPdpEntity.setSite(pdp.getSite());
/*
* End transaction.
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;
isWaitingForActivation = false;
isNowActivating = false;
logger.warn("DelayActivateClass.run: caught an unexpected exception "
- + "calling PolicyEngine.manager.activate: ", e);
+ + "calling PolicyEngineConstants.getManager().activate: ", e);
}
}
}
// these may be overridden by junit tests
protected PolicyEngine getPolicyEngineManager() {
- return PolicyEngine.manager;
+ return PolicyEngineConstants.getManager();
}
protected Timer makeTimer() {
@Test
public void testNullSafeCompare() {
// self, when null
- pdp.setSiteName(null);
+ pdp.setSite(null);
assertEquals(0, pdp.comparePriority(pdp));
// both null
};
pdp2.setPdpId(PDP_ID);
- pdp2.setSiteName(SITE2);
+ pdp2.setSite(SITE2);
pdp2.setPriority(PRIORITY);
// should use overridden comparison method
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);
private boolean designated;
private int priority;
private Date updatedDate;
- private String siteName;
+ private String site;
private Date designatedDate;
}
}
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;
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;
// 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(): {}",
// 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(): {}",
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;
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;
// 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(): {}",
// 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(): {}",
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);
// 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(): {}",
// 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());
// 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(): {}",
// 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());
// 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(): {}",
// 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());
// 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(): {}",
// 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());
// 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(): {}",
// 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());
// 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(): {}",
import org.onap.policy.drools.protocol.configuration.ControllerConfiguration;\r
import org.onap.policy.drools.protocol.configuration.PdpdConfiguration;\r
import org.onap.policy.drools.system.PolicyController;\r
+import org.onap.policy.drools.system.PolicyControllerConstants;\r
import org.onap.policy.drools.system.PolicyEngine;\r
import org.slf4j.Logger;\r
import org.slf4j.LoggerFactory;\r
public boolean afterDeliver(DroolsController controller, TopicSink sink, Object fact, String json,\r
boolean success) {\r
if (success) {\r
- Logger controllerLogger = LoggerFactory.getLogger(PolicyController.factory.get(controller).getName());\r
+ Logger controllerLogger = LoggerFactory\r
+ .getLogger(PolicyControllerConstants.getFactory().get(controller).getName());\r
controllerLogger.info("[OUT|{}|{}]{}{}", sink.getTopicCommInfrastructure(), sink.getTopic(),\r
System.lineSeparator(), json);\r
}\r
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;\r
import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink;\r
import org.onap.policy.drools.controller.DroolsController;\r
-import org.onap.policy.drools.controller.logging.ControllerLoggingFeature;\r
-import org.onap.policy.drools.properties.DroolsProperties;\r
+import org.onap.policy.drools.controller.DroolsControllerConstants;\r
+import org.onap.policy.drools.properties.DroolsPropertyConstants;\r
import org.onap.policy.drools.protocol.configuration.ControllerConfiguration;\r
import org.onap.policy.drools.protocol.configuration.PdpdConfiguration;\r
import org.onap.policy.drools.system.PolicyController;\r
-import org.onap.policy.drools.system.PolicyEngine;\r
+import org.onap.policy.drools.system.PolicyEngineConstants;\r
import org.onap.policy.drools.util.KieUtils;\r
\r
/**\r
JUNIT_KJAR_DRL_PATH, Paths.get(JUNIT_KMODULE_DRL_PATH).toFile());\r
\r
controllerProps = new Properties();\r
- controllerProps.put(DroolsProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME);\r
- controllerProps.put(DroolsProperties.RULES_GROUPID, TEST_GROUP_ID);\r
- controllerProps.put(DroolsProperties.RULES_ARTIFACTID, TEST_ARTIFACT_ID);\r
- controllerProps.put(DroolsProperties.RULES_VERSION, TEST_VERSION);\r
+ controllerProps.put(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME);\r
+ controllerProps.put(DroolsPropertyConstants.RULES_GROUPID, TEST_GROUP_ID);\r
+ controllerProps.put(DroolsPropertyConstants.RULES_ARTIFACTID, TEST_ARTIFACT_ID);\r
+ controllerProps.put(DroolsPropertyConstants.RULES_VERSION, TEST_VERSION);\r
\r
- policyController = PolicyEngine.manager.createPolicyController(TEST_CONTROLLER_NAME, controllerProps);\r
+ policyController = PolicyEngineConstants.getManager().createPolicyController(TEST_CONTROLLER_NAME,\r
+ controllerProps);\r
\r
message = "{\"requestID\":\"38adde30-cc22-11e8-a8d5-f2801f1b9fd1\",\"entity\":\"controller\",\"controllers\":"\r
+ "[{\"name\":\"test-controller\",\"drools\":{\"groupId\":\"org.onap.policy.drools.test\","\r
\r
final ControllerLoggingFeature nlf = new ControllerLoggingFeature();\r
\r
- DroolsController droolsController = DroolsController.factory.get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);\r
+ DroolsController droolsController =\r
+ DroolsControllerConstants.getFactory().get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);\r
\r
NoopTopicSink sinkTopic = new NoopTopicSink(Arrays.asList(TEST_SERVER), TEST_TOPIC);\r
\r
\r
final ControllerLoggingFeature nlf = new ControllerLoggingFeature();\r
\r
- DroolsController droolsController = DroolsController.factory.get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);\r
+ DroolsController droolsController =\r
+ DroolsControllerConstants.getFactory().get(TEST_GROUP_ID, TEST_ARTIFACT_ID, TEST_VERSION);\r
\r
NoopTopicSink sinkTopic = new NoopTopicSink(Arrays.asList(TEST_SERVER), TEST_TOPIC);\r
\r
public void afterOnTopicEventSuccess() {\r
final ControllerLoggingFeature nlf = new ControllerLoggingFeature();\r
\r
- nlf.afterOnTopicEvent(PolicyEngine.manager, pdpdNotification, CommInfrastructure.UEB, TEST_TOPIC, message);\r
+ nlf.afterOnTopicEvent(PolicyEngineConstants.getManager(), pdpdNotification, CommInfrastructure.UEB, TEST_TOPIC,\r
+ message);\r
\r
assertEquals(1, events.size());\r
}\r
config.setName("test-controller-2");\r
notification.setControllers(Arrays.asList(config));\r
\r
- nlf.afterOnTopicEvent(PolicyEngine.manager, notification, CommInfrastructure.UEB, TEST_TOPIC, message);\r
+ nlf.afterOnTopicEvent(PolicyEngineConstants.getManager(), notification, CommInfrastructure.UEB, TEST_TOPIC,\r
+ message);\r
\r
assertEquals(0, events.size());\r
}\r
* 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.
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;
private BasicDataSource dataSource;
/**
- * UUID.
+ * UUID.
*/
private static final UUID uuid = UUID.randomUUID();
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
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);
/**
* Make data source.
- *
+ *
* @return a new, pooled data source
* @throws Exception exception
*/
* ============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.
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
@BeforeClass
public static void setUpBeforeClass() throws Exception {
- SystemPersistence.manager.setConfigurationDir("src/test/resources");
+ SystemPersistenceConstants.getManager().setConfigurationDir("src/test/resources");
}
@Before
* ============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.
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;
public static void setup() {
getDbConnection();
createTable();
- SystemPersistence.manager.setConfigurationDir("src/test/resources");
+ SystemPersistenceConstants.getManager().setConfigurationDir("src/test/resources");
distLockFeat = new DistributedLockingFeature();
distLockFeat.afterStart(null);
}
* 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.
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;
/**
* 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());
/**
* Assert Log Levels are the same between an EELF Logger and an SLF4J Logger.
- *
+ *
* @param eelfLogger EELF Logger
* @param slf4jLogger SLF4J Logger
*/
/* 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));
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 */
*/
public interface HealthCheck extends Startable {
- /**
- * Healthcheck Monitor.
- */
- public static final HealthCheck monitor = new HealthCheckMonitor();
-
/**
* Healthcheck Report.
*/
--- /dev/null
+/*
+ * ============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
+ }
+}
* 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.
/**
* Logger.
*/
- private static Logger logger = LoggerFactory.getLogger(HealthCheckFeature.class);
+ private static Logger logger = LoggerFactory.getLogger(HealthCheckFeature.class);
/**
* Properties Configuration Name.
@Override
public boolean afterStart(PolicyEngine engine) {
try {
- getMonitor().start();
+ getManager().start();
} catch (IllegalStateException e) {
logger.error("Healthcheck Monitor cannot be started", e);
}
@Override
public boolean afterShutdown(PolicyEngine engine) {
try {
- getMonitor().stop();
+ getManager().stop();
} catch (IllegalStateException e) {
logger.error("Healthcheck Monitor cannot be stopped", e);
}
/**
* Gets the monitor.
- *
- * @return the healthcheck monitor
+ *
+ * @return the healthcheck manager
*/
- public HealthCheck getMonitor() {
- return HealthCheck.monitor;
+ public HealthCheck getManager() {
+ return HealthCheckConstants.getManager();
}
}
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;
/**
* 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.
// the following methods may be overridden by junit tests
protected PolicyEngine getEngineManager() {
- return PolicyEngine.manager;
+ return PolicyEngineConstants.getManager();
}
protected HttpServletServerFactory getServerFactory() {
}
protected Properties getPersistentProperties(String propertyName) {
- return SystemPersistence.manager.getProperties(propertyName);
+ return SystemPersistenceConstants.getManager().getProperties(propertyName);
}
}
* ============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.
@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();
}
}
* ============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.
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;
*/
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";
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);
}
}
- feature.afterShutdown(PolicyEngine.manager);
+ feature.afterShutdown(PolicyEngineConstants.getManager());
}
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 {
}
@Override
- public HealthCheck getMonitor() {
+ public HealthCheck getManager() {
return checker;
}
private List<HttpServletServer> servers;
private List<HttpClient> clients;
private PolicyEngine engineMgr;
- private HealthCheckMonitor monitor;
+ private HealthCheckManager monitor;
/**
* Initializes the object to be tested.
@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() {
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;
* 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);
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();
}
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;
}
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);
protected abstract boolean undeployPolicy(@NonNull PolicyController controller, @NonNull ToscaPolicy policy);
- protected LifecycleStateRunning(LifecycleFsm manager) {
- super(manager);
- }
-
@Override
public boolean start() {
logger.warn("{}: start", this);
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;
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);
}
/**
* 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);
}
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 {
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();
}
@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);
}
}
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;
@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
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;
@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) {
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;
/**
HttpServletServerFactoryInstance.getServerFactory().destroy();
HttpClientFactoryInstance.getClientFactory().destroy();
- SystemPersistence.manager.setConfigurationDir("target/test-classes");
+ SystemPersistenceConstants.getManager().setConfigurationDir("target/test-classes");
HttpClientFactoryInstance.getClientFactory().build(
BusTopicParams.builder()
import org.onap.policy.common.endpoints.features.NetLoggerFeatureApi;\r
import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;\r
import org.onap.policy.drools.features.PolicyControllerFeatureApi;\r
-import org.onap.policy.drools.persistence.SystemPersistence;\r
+import org.onap.policy.drools.persistence.SystemPersistenceConstants;\r
import org.onap.policy.drools.system.PolicyController;\r
import org.slf4j.Logger;\r
import org.slf4j.LoggerFactory;\r
* @return the properties for this feature.\r
*/\r
protected Properties getFeatureProps() {\r
- return SystemPersistence.manager.getProperties(FEATURE_NAME);\r
+ return SystemPersistenceConstants.getManager().getProperties(FEATURE_NAME);\r
}\r
\r
/**\r
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;
* @return the properties for the specified feature
*/
protected Properties getProperties(String featName) {
- return SystemPersistence.manager.getProperties(featName);
+ return SystemPersistenceConstants.getManager().getProperties(featName);
}
/**
* @return the policy controller associated with a drools controller
*/
protected PolicyController getController(DroolsController droolsController) {
- return PolicyController.factory.get(droolsController);
+ return PolicyControllerConstants.getFactory().get(droolsController);
}
/**
* 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.
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;
/**
* 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
/**
* Should only be used by junit tests.
- *
+ *
* @return the current state
*/
protected State getCurrent() {
/**
* 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
/**
* 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) {
/**
* Sets the server-side filter for the internal topic.
- *
+ *
* @param filter new filter to be used
*/
private void setFilter(Map<String, Object> filter) {
/**
* Handles an event from the internal topic.
- *
+ *
* @param commType comm infrastructure
* @param topic2 topic
* @param event event
* 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
/**
* 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
/**
* Handles an event from an external topic.
- *
+ *
* @param protocol protocol
* @param topic2 topic
* @param event event
/**
* 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
/**
* 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
/**
* 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
*/
/**
* 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
/**
* Makes a {@link Forward}, and validates its contents.
- *
+ *
* @param protocol protocol
* @param topic2 topic
* @param event event
/**
* Injects an event into the controller.
- *
+ *
* @param event event
*/
private void inject(Forward event) {
* 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) {
/**
* Constructor.
- *
+ *
* @param task task to execute when this timer runs
*/
public TimerAction(StateTimerTask task) {
}
}
}
-
+
/*
* 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
*/
/**
* Creates a DMaaP manager.
- *
+ *
* @param topic name of the internal DMaaP topic
* @return a new DMaaP manager
* @throws PoolingFeatureException if an error occurs
/**
* Creates a scheduled thread pool.
- *
+ *
* @return a new scheduled thread pool
*/
protected ScheduledThreadPoolExecutor makeScheduler() {
/**
* 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
* @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);
}
}
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;
public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngineFeatureApi {
private static final Logger logger = LoggerFactory.getLogger(PersistenceFeature.class);
-
+
/** KieService factory. */
private KieServices kieSvcFact;
/** 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;
return (ContainerAdjunct) rval;
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
return 1;
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
return null;
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
return null;
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
}
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
}
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
return false;
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
return false;
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
return false;
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
/**
* Get thread name.
- *
+ *
* @return the String to use as the thread name */
private String getThreadName() {
return "Session " + session.getFullName() + " (persistent)";
/* 'ThreadModel' interface */
/*=========================*/
- /**
+ /**
* {@inheritDoc}.
**/
@Override
thread.start();
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
}
}
- /**
+ /**
* {@inheritDoc}.
**/
@Override
/* 'Runnable' interface */
/*======================*/
- /**
+ /**
* {@inheritDoc}.
**/
@Override
* @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());
}
/**
public static class PersistenceFeatureException extends RuntimeException {
private static final long serialVersionUID = 1L;
- /**
+ /**
* Constructor.
* */
public PersistenceFeatureException(Exception ex) {
* 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.
* 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 =
/**
* {@inheritDoc}.
- *
+ *
* @return true if locked or false if failed
*/
@Override
/**
* {@inheritDoc}.
- *
+ *
* @throws Exception exception
*/
@Override
/**
* {@inheritDoc}.
- *
- * @throws Exception exception
+ *
+ * @throws Exception exception
*/
@Override
public boolean isLocked() {
@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);
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;
.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(): "
/** 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.
*
--- /dev/null
+/*-
+ * ============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
+ }
+}
* @return the test transaction manager
*/
protected TestTransaction getTestTransMgr() {
- return TestTransaction.manager;
+ return TestTransactionConstants.getManager();
}
}
}
if (!getCurrentThread().isInterrupted()) {
- doSleep(TestTransaction.DEFAULT_TT_TASK_SLEEP);
+ doSleep(TestTransactionConstants.DEFAULT_TT_TASK_SLEEP);
}
}
} catch (final InterruptedException e) {
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
fpc);
}
fpcs.put(session, fpc);
- drools.getContainer().insert(session, new EventObject(TestTransaction.TT_UUID));
+ drools.getContainer().insert(session, new EventObject(TestTransactionConstants.TT_UUID));
}
}
@Test
public void testTestTransactionImpl() {
- assertNotNull(TtImpl.manager);
+ assertNotNull(TestTransactionConstants.getManager());
}
@Test
// 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();
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;
/**
* Start up.
- *
+ *
* @throws IOException exception
*/
@BeforeClass
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
latch.countDown();
}
};
- }
+ }
};
impl.register(controller);
- assertNotNull(TestTransaction.manager);
+ assertNotNull(TestTransactionConstants.getManager());
/*
* Unregistering the controller should terminate its TestTransaction thread if it hasn't already
/**
* 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
/** 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) {
}
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) {
<artifactId>policy-utils</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.projectlombok</groupId>
+ <artifactId>lombok</artifactId>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
* 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.
/**
* Get name.
- *
+ *
* @return the name of the container, which is the String equivalent of the 'ReleaseId'. It has
* the form:
*
/**
* Get kie container.
- *
+ *
* @return the associated 'KieContainer' instance
*/
public KieContainer getKieContainer() {
/**
* Get class loader.
- *
+ *
* @return the 'ClassLoader' associated with the 'KieContainer' instance
*/
public ClassLoader getClassLoader() {
/**
* Get group Id.
- *
+ *
* @return the Maven GroupId of the top-level artifact wrapped by the container.
*/
public String getGroupId() {
/**
* Get artifact id.
- *
+ *
* @return the Maven ArtifactId of the top-level artifact wrapped by the container.
*/
public String getArtifactId() {
/**
* Get version.
- *
+ *
* @return the version of the top-level artifact wrapped by the container (this may change as
* updates occur)
*/
// 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;
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) {
}
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;
}
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) {
/**
* Get policy containers.
- *
+ *
* @return all existing 'PolicyContainer' instances
*/
public static Collection<PolicyContainer> getPolicyContainers() {
/**
* 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();
}
session.getKieSession().dispose();
// notify features
- for (PolicySessionFeatureApi feature : PolicySessionFeatureApi.impl.getList()) {
+ for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) {
try {
feature.disposeKieSession(session);
} catch (Exception e) {
session.getKieSession().destroy();
// notify features
- for (PolicySessionFeatureApi feature : PolicySessionFeatureApi.impl.getList()) {
+ for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) {
try {
feature.destroyKieSession(session);
} catch (Exception e) {
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) {
// 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;
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
* 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
--- /dev/null
+/*-
+ * ============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
+ }
+}
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
*/
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.
*/
--- /dev/null
+/*
+ * ============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
+ }
+}
* ============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.
/**
* Get instance.
- *
+ *
* @return the manager singleton
*/
public static PolicyResourceLockManager getInstance() {
/**
* Is locked.
- *
+ *
* @throws IllegalArgumentException if the resourceId is {@code null}
*/
@Override
}
- 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)
/**
* Is locked by.
- *
+ *
* @throws IllegalArgumentException if the resourceId or owner is {@code null}
*/
@Override
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)
* 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
/**
* 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
/**
* Get implementers.
- *
+ *
* @return the list of feature implementers
*/
protected List<PolicyResourceLockFeatureApi> getImplementers() {
- return PolicyResourceLockFeatureApi.impl.getList();
+ return PolicyResourceLockFeatureApiConstants.getImpl().getList();
}
/**
private static class Singleton {
private static final PolicyResourceLockManager instance = new PolicyResourceLockManager();
-
+
/**
* Not invoked.
*/
* ============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.
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
+ }
}
* 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.
*/
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();
/**
* 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);
/**
* delivers "event" to "sink".
- *
+ *
* @param sink destination
* @param event event
* @return true if successful, false if a failure has occurred.
/**
* 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
/**
* fetches a class from the model.
- *
+ *
* @param className the class to fetch
* @return the actual class object, or null if not found
*/
/**
* 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
*/
/**
* gets the classnames of facts as well as the current count.
- *
+ *
* @param sessionName the session name
* @return map of class to count
*/
/**
* gets the count of facts for a given session.
- *
+ *
* @param sessionName the session name
* @return the fact count
*/
/**
* 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?
/**
* 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
/**
* halts and permanently releases all resources.
- *
+ *
*/
void halt();
}
--- /dev/null
+/*
+ * ============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
+ }
+}
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;
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);
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;
*/
public class MavenDroolsController implements DroolsController {
+ private static final String FACT_RETRIEVE_ERROR = "Object cannot be retrieved from fact {}";
+
/**
* logger.
*/
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);
classNames.put(className, 1);
}
} catch (Exception e) {
- logger.warn("Object cannot be retrieved from fact {}", fact, e);
+ logger.warn(FACT_RETRIEVE_ERROR, fact, e);
}
}
kieSession.delete(factHandle);
}
} catch (Exception e) {
- logger.warn("Object cannot be retrieved from fact {}", factHandle, e);
+ logger.warn(FACT_RETRIEVE_ERROR, factHandle, e);
}
}
return true;
}
} catch (Exception e) {
- logger.warn("Object cannot be retrieved from fact {}", factHandle, e);
+ logger.warn(FACT_RETRIEVE_ERROR, factHandle, e);
}
}
return false;
@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
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;
}
}
@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);
}
// 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) {
* 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.
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;
@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
}
@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<>();
}
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;
/**
boolean success) {
return false;
}
-
- /**
- * Feature providers implementing this interface.
- */
- public static final OrderedServiceImpl<DroolsControllerFeatureApi> providers =
- new OrderedServiceImpl<>(DroolsControllerFeatureApi.class);
}
--- /dev/null
+/*-
+ * ============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
+ }
+}
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'.
--- /dev/null
+/*
+ * ============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
+ }
+}
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;
* 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.
--- /dev/null
+/*-
+ * ============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
+ }
+}
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;
/**
* Configuration directory.
*/
- protected Path configurationDirectory = Paths.get(DEFAULT_CONFIGURATION_DIR);
+ protected Path configurationDirectory = Paths.get(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR);
/**
* Logger.
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);
}
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);
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) {
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) {
* 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.
--- /dev/null
+/*
+ * ============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
+ }
+}
*/
public interface EventProtocolCoder {
- /**
- * singleton reference to the global event protocol coder.
- */
- public static EventProtocolCoder manager = new MultiplexorEventProtocolCoder();
-
public static class CoderFilters {
/**
--- /dev/null
+/*
+ * ============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
+ }
+}
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;
* 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);
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);
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) {
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);
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);
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()) {
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);
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;
* Tools used for encoding/decoding using GSON.
*/
class GsonProtocolCoderToolset extends ProtocolCoderToolset {
+ private static final String FETCH_CLASS_EX_MSG = "cannot fetch application class ";
+
/**
* Logger.
*/
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");
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) {
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 {
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);
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;
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.
@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();
}
/**
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();
}
/**
@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
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();
}
/**
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();
@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();
}
/**
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();
@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();
}
/**
@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();
}
/**
@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();
}
/**
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();
}
@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();
}
/**
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();
}
}
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();
}
}
@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();
}
}
@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();
}
}
@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();
}
/**
@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();
}
/**
.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();
}
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();
@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();
}
/**
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();
}
/**
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();
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();
}
}
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);
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();
}
}
@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();
}
/**
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();
@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();
}
/**
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();
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();
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();
}
}
}
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();
}
}
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();
}
}
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();
}
}
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();
}
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();
}
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();
}
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();
}
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();
}
}
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();
}
}
@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();
}
}
@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();
}
}
@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();
}
}
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();
}
}
@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();
}
}
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();
}
}
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()) {
+ "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();
}
}
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();
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 ..
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();
@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();
}
/**
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();
}
}
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();
}
}
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();
}
/**
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();
}
/**
.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();
* @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;
this.msg = msg;
}
}
-
- /**
- * Feed Ports into Resources.
- */
- public enum Inputs {
- configuration,
- }
-
- /**
- * Resource Toggles.
- */
- public enum Switches {
- activation, lock,
- }
}
* ============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.
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.
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);
}
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;
}
protected List<PolicyControllerFeatureApi> getProviders() {
- return PolicyControllerFeatureApi.providers.getList();
+ return PolicyControllerFeatureApiConstants.getProviders().getList();
}
}
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;
/* 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);
}
.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();
}
logger.warn(
LoggerUtil.TRANSACTION_LOG_MARKER,
"Main: cannot start {} (bad state) because of {}",
- PolicyEngine.manager,
+ PolicyEngineConstants.getManager(),
e.getMessage(),
e);
} catch (final Exception e) {
logger.warn(
LoggerUtil.TRANSACTION_LOG_MARKER,
"Main: cannot start {} because of {}",
- PolicyEngine.manager,
+ PolicyEngineConstants.getManager(),
e.getMessage(),
e);
System.exit(1);
/* 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)
.setTargetServiceName("start");
final PolicyController controller =
- PolicyEngine.manager.createPolicyController(controllerName, controllerProperties);
+ PolicyEngineConstants.getManager().createPolicyController(controllerName, controllerProperties);
controller.start();
trans
* 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.
*/
public interface PolicyController extends Startable, Lockable {
- /**
- * Factory that tracks and manages Policy Controllers.
- */
- static PolicyControllerFactory factory = new IndexedPolicyControllerFactory();
-
/**
* name of this Policy Controller.
*/
/**
* Update maven configuration.
- *
+ *
* @param newDroolsConfiguration new drools configuration
* @return true if the update was successful, false otherwise
*/
/**
* 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
/**
* halts and permanently releases all resources.
- *
+ *
* @throws IllegalStateException throws illegal state exception
*/
void halt();
--- /dev/null
+/*
+ * ============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
+ }
+}
* 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.
--- /dev/null
+/*-
+ * ============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
+ }
+}
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;
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;
.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);
}
}
// 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 ("
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);
// 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) {
}
protected PolicyControllerFactory getControllerFactory() {
- return PolicyController.factory;
+ return PolicyControllerConstants.getFactory();
}
protected void startPdpJmxListener() {
}
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();
}
}
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;
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;
}
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]));
}
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);
// the following methods may be overridden by junit tests
protected SystemPersistence getPersistenceManager() {
- return SystemPersistence.manager;
+ return SystemPersistenceConstants.getManager();
}
protected TopicEndpoint getEndpointManager() {
}
protected DroolsControllerFactory getDroolsFactory() {
- return DroolsController.factory;
+ return DroolsControllerConstants.getFactory();
}
protected List<PolicyControllerFeatureApi> getProviders() {
- return PolicyControllerFeatureApi.providers.getList();
+ return PolicyControllerFeatureApiConstants.getProviders().getList();
}
}
* ============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.
@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");
@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");
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]");
}
}
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;
}
};
- assertSame(EventProtocolCoder.manager, drools.getCoderManager());
- assertSame(DroolsControllerFeatureApi.providers, drools.getDroolsProviders());
+ assertSame(EventProtocolCoderConstants.getManager(), drools.getCoderManager());
+ assertSame(DroolsControllerFeatureApiConstants.getProviders(), drools.getDroolsProviders());
}
@Test
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 {
@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
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.
@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();
}
}
- 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);
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);
}
}
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;
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() {
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;
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);
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();
@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();
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);
}
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);
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;
// 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);
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;
*/
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) {
}
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) {
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);
}
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
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
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());
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
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());
}
}
package org.onap.policy.drools.utils.logging;
import java.time.Instant;
-import org.onap.policy.common.utils.network.NetworkUtil;
/**
* MDC Transaction Utility Class.
* <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.
--- /dev/null
+/*-
+ * ============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
+ }
+}
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;
private String invocationId;
private String virtualServerName;
- private String server;
+ private String serverName;
private String serverIpAddress;
private String serverFqdn;
private String statusCode;
private String responseCode;
private String responseDescription;
- private String severity;
+ private String theSeverity;
private String alertSeverity;
private String targetEntity;
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) {
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) {
@Override
public String getServer() {
- return this.server;
+ return this.serverName;
}
@Override
@Override
public MdcTransaction setSeverity(String severity) {
- this.severity = severity;
+ this.theSeverity = severity;
return this;
}
@Override
public String getSeverity() {
- return severity;
+ return theSeverity;
}
@Override
@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;
}
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('\'');
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('\'');
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) {
}
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)
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());