import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
-import java.util.Properties;
-import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.onap.policy.common.im.MonitorTime;
//Create an instance of the Observer
- PmStandbyStateChangeNotifier pmNotifier = new PmStandbyStateChangeNotifier();
+ var pmNotifier = new PmStandbyStateChangeNotifier();
//Register the PMStandbyStateChangeNotifier Observer
stateManagementFeature.addObserver(pmNotifier);
private static void initializePersistence(String configDir) {
//Get the Active Standby properties
try {
- Properties activeStandbyProperties =
+ var activeStandbyProperties =
PropertyUtil.getProperties(configDir + "/feature-active-standby-management.properties");
ActiveStandbyProperties.initProperties(activeStandbyProperties);
logger.info("initializePersistence: ActiveStandbyProperties success");
logger.error("ActiveStandbyFeature: initializePersistence ActiveStandbyProperties", e);
}
- DroolsPdpsConnector conn = getDroolsPdpsConnector("activeStandbyPU");
+ var conn = getDroolsPdpsConnector("activeStandbyPU");
String resourceName = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME);
if (resourceName == null) {
throw new NullPointerException();
propMap.put(PersistenceUnitProperties.TARGET_DATABASE,
ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_TYPE));
- EntityManagerFactory emf = Persistence.createEntityManagerFactory(
- pu, propMap);
+ var emf = Persistence.createEntityManagerFactory(pu, propMap);
return new JpaDroolsPdpsConnector(emf);
}
import javax.persistence.NamedQuery;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
+import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.onap.policy.common.im.MonitorTime;
@NamedQuery(name = "DroolsPdpEntity.deleteAll", query = "DELETE FROM DroolsPdpEntity WHERE 1=1")
@Getter
@Setter
+@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = true)
public class DroolsPdpEntity extends DroolsPdpObject implements Serializable {
private static final long serialVersionUID = 1L;
package org.onap.policy.drools.activestandby;
import java.util.Date;
+import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
+@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = true)
public class DroolsPdpImpl extends DroolsPdpObject {
private boolean designated;
* ============LICENSE_START=======================================================
* feature-active-standby-management
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 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.
@Override
public int hashCode() {
- final int prime = 31;
- int result = 1;
+ final var prime = 31;
+ var result = 1;
result = prime * result + (this.getPdpId() == null ? 0 : this.getPdpId().hashCode());
return result;
}
import java.util.Date;
import java.util.List;
import java.util.Objects;
-import java.util.Timer;
import java.util.TimerTask;
import lombok.Getter;
import lombok.Setter;
this.isDesignated = false;
// The interval between checks of the DesignationWaiter to be sure it is running.
- int pdpCheckInterval = 3000;
+ var pdpCheckInterval = 3000;
try {
pdpCheckInterval = Integer.parseInt(ActiveStandbyProperties.getProperty(
ActiveStandbyProperties.PDP_CHECK_INVERVAL));
logger.error("Could not get pdpUpdateInterval property. Using default {} ", pdpUpdateInterval, e);
}
- Date now = currentTime.getDate();
+ var now = currentTime.getDate();
// Retrieve the ms since the epoch
final long nowMs = now.getTime();
// Create the timer which will update the updateDate in DroolsPdpEntity table.
// This is the heartbeat
- Timer updateWorker = Factory.getInstance().makeTimer();
+ var updateWorker = Factory.getInstance().makeTimer();
// Schedule the TimerUpdateClass to run at 100 ms and run at pdpCheckInterval ms thereafter
// NOTE: The first run of the TimerUpdateClass results in myPdp being added to the
updateWorker.scheduleAtFixedRate(new TimerUpdateClass(), 100, pdpCheckInterval);
// Create the timer which will run the election algorithm
- Timer waitTimer = Factory.getInstance().makeTimer();
+ var waitTimer = Factory.getInstance().makeTimer();
// Schedule it to start in startMs ms
// (so it will run after the updateWorker and run at pdpUpdateInterval ms thereafter
long startMs = getDWaiterStartMs();
- DesignationWaiter designationWaiter = new DesignationWaiter();
+ var designationWaiter = new DesignationWaiter();
waitTimer.scheduleAtFixedRate(designationWaiter, startMs, pdpUpdateInterval);
waitTimerLastRunDate = new Date(nowMs + startMs);
logger.debug("DesignatedWaiter.run: myPdp: {}; Returning, isDesignated= {}",
isDesignated, myPdp.getPdpId());
- Date tmpDate = currentTime.getDate();
+ var tmpDate = currentTime.getDate();
logger.debug("DesignatedWaiter.run (end of run) waitTimerLastRunDate = {}", tmpDate);
waitTimerLastRunDate = tmpDate;
*/
public List<DroolsPdp> santizeDesignatedList(List<DroolsPdp> listOfDesignated) {
- boolean containsDesignated = false;
- boolean containsHotStandby = false;
+ var containsDesignated = false;
+ var containsHotStandby = false;
List<DroolsPdp> listForRemoval = new ArrayList<>();
for (DroolsPdp pdp : listOfDesignated) {
logger.debug("DesignatedWaiter.run sanitizing: pdp = {}"
logger.debug("DesignatedWaiter.run: myPdp: {} listOfDesignated.size(): {}", myPdp.getPdpId(),
listOfDesignated.size());
- DesignatedData data = new DesignatedData();
+ var data = new DesignatedData();
for (DroolsPdp pdp : listOfDesignated) {
DroolsPdp rejectedPdp;
synchronized (checkWaitTimerLock) {
try {
logger.debug("checkWaitTimer: entry");
- Date now = currentTime.getDate();
+ var now = currentTime.getDate();
long nowMs = now.getTime();
long waitTimerMs = waitTimerLastRunDate.getTime();
}
private long getDWaiterStartMs() {
- Date now = currentTime.getDate();
+ var now = currentTime.getDate();
// Retrieve the ms since the epoch
long nowMs = now.getTime();
package org.onap.policy.drools.activestandby;
import java.util.Collection;
-import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.persistence.LockModeType;
-import javax.persistence.Query;
import lombok.AllArgsConstructor;
import org.onap.policy.common.im.MonitorTime;
import org.onap.policy.common.utils.time.CurrentTime;
@Override
public Collection<DroolsPdp> getDroolsPdps() {
//return a list of all the DroolsPdps in the database
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
try {
em.getTransaction().begin();
- Query droolsPdpsListQuery = em.createQuery("SELECT p FROM DroolsPdpEntity p");
- List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
+ var droolsPdpsListQuery = em.createQuery("SELECT p FROM DroolsPdpEntity p", DroolsPdp.class);
+ List<DroolsPdp> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
.setFlushMode(FlushModeType.COMMIT).getResultList();
LinkedList<DroolsPdp> droolsPdpsReturnList = new LinkedList<>();
- for (Object o : droolsPdpsList) {
- if (!(o instanceof DroolsPdp)) {
- continue;
- }
+ for (DroolsPdp droolsPdp : droolsPdpsList) {
//Make sure it is not a cached version
- DroolsPdp droolsPdp = (DroolsPdp) o;
em.refresh(droolsPdp);
droolsPdpsReturnList.add(droolsPdp);
if (logger.isDebugEnabled()) {
logger.debug("update: Entering, pdpId={}", pdp.getPdpId());
//this is to update our own pdp in the database
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
try {
em.getTransaction().begin();
- Query droolsPdpsListQuery = em.createQuery(SELECT_PDP_BY_ID);
+ var droolsPdpsListQuery = em.createQuery(SELECT_PDP_BY_ID, DroolsPdpEntity.class);
droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdp.getPdpId());
- List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
+ List<DroolsPdpEntity> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
.setFlushMode(FlushModeType.COMMIT).getResultList();
DroolsPdpEntity droolsPdpEntity;
- if (droolsPdpsList.size() == 1 && (droolsPdpsList.get(0) instanceof DroolsPdpEntity)) {
- droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0);
+ if (droolsPdpsList.size() == 1) {
+ droolsPdpEntity = droolsPdpsList.get(0);
em.refresh(droolsPdpEntity); //Make sure we have current values
- Date currentDate = currentTime.getDate();
+ var currentDate = currentTime.getDate();
long difference = currentDate.getTime() - droolsPdpEntity.getUpdatedDate().getTime();
//just set some kind of default here
long pdpTimeout = 15000;
boolean isCurrent = isCurrent(pdp);
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
try {
if (!isCurrent && pdp.isDesignated()) {
em.getTransaction().begin();
- Query droolsPdpsListQuery = em.createQuery(SELECT_PDP_BY_ID);
+ var droolsPdpsListQuery = em.createQuery(SELECT_PDP_BY_ID, DroolsPdpEntity.class);
droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdp.getPdpId());
- List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
+ List<DroolsPdpEntity> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
.setFlushMode(FlushModeType.COMMIT).getResultList();
- if (droolsPdpsList.size() == 1 && droolsPdpsList.get(0) instanceof DroolsPdpEntity) {
+ if (droolsPdpsList.size() == 1) {
logger.debug("isPdpCurrent: PDP={} designated but not current; setting designated to false",
pdp.getPdpId());
- DroolsPdpEntity droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0);
+ var droolsPdpEntity = droolsPdpsList.get(0);
droolsPdpEntity.setDesignated(false);
em.getTransaction().commit();
} else {
try {
em = emf.createEntityManager();
em.getTransaction().begin();
- Query droolsPdpsListQuery = em
- .createQuery(SELECT_PDP_BY_ID);
+ var droolsPdpsListQuery = em
+ .createQuery(SELECT_PDP_BY_ID, DroolsPdpEntity.class);
droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdp.getPdpId());
- List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(
+ List<DroolsPdpEntity> droolsPdpsList = droolsPdpsListQuery.setLockMode(
LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (droolsPdpsList.size() == 1
- && droolsPdpsList.get(0) instanceof DroolsPdpEntity) {
- DroolsPdpEntity droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList
- .get(0);
+ if (droolsPdpsList.size() == 1) {
+ var droolsPdpEntity = droolsPdpsList.get(0);
logger.debug("setDesignated: PDP={}"
+ " found, designated= {}"
* Get droolspdpentity record for this PDP and mark DESIGNATED as
* false.
*/
- Query droolsPdpsListQuery = em
- .createQuery(SELECT_PDP_BY_ID);
+ var droolsPdpsListQuery = em
+ .createQuery(SELECT_PDP_BY_ID, DroolsPdpEntity.class);
droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdpId);
- List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(
+ List<DroolsPdpEntity> droolsPdpsList = droolsPdpsListQuery.setLockMode(
LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- DroolsPdpEntity droolsPdpEntity;
- if (droolsPdpsList.size() == 1
- && (droolsPdpsList.get(0) instanceof DroolsPdpEntity)) {
- droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0);
+ if (droolsPdpsList.size() == 1) {
+ var droolsPdpEntity = droolsPdpsList.get(0);
droolsPdpEntity.setDesignated(false);
em.persist(droolsPdpEntity);
logger.debug("standDownPdp: PDP={} persisted as non-designated.", pdpId);
logger.debug("hasDesignatedPdpFailed: Entering, pdps.size()={}", pdps.size());
- boolean failed = true;
- boolean foundDesignatedPdp = false;
+ var failed = true;
+ var foundDesignatedPdp = false;
for (DroolsPdp pdp : pdps) {
logger.debug("isCurrent: Entering, pdpId={}", pdp.getPdpId());
- boolean current = false;
+ var current = false;
// Return if the current PDP is considered "current" based on whatever
// time box that may be.
// If the the PDP is not current, we should mark it as not primary in
// the database
- Date currentDate = currentTime.getDate();
+ var currentDate = currentTime.getDate();
long difference = currentDate.getTime()
- pdp.getUpdatedDate().getTime();
// just set some kind of default here
try {
em = emf.createEntityManager();
em.getTransaction().begin();
- Query droolsPdpsListQuery = em
+ var droolsPdpsListQuery = em
.createQuery(SELECT_PDP_BY_ID);
droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdpId);
List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(
/*
* Start transaction
*/
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
try {
em.getTransaction().begin();
/*
* Insert record.
*/
- DroolsPdpEntity droolsPdpEntity = new DroolsPdpEntity();
+ var droolsPdpEntity = new DroolsPdpEntity();
em.persist(droolsPdpEntity);
droolsPdpEntity.setPdpId(pdp.getPdpId());
droolsPdpEntity.setDesignated(pdp.isDesignated());
/*
* Start transaction
*/
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
try {
em.getTransaction().begin();
- Query droolsPdpsListQuery = em
+ var droolsPdpsListQuery = em
.createQuery("SELECT p FROM DroolsPdpEntity p");
@SuppressWarnings("unchecked")
List<DroolsPdp> droolsPdpsList = droolsPdpsListQuery.setLockMode(
/*
* Start transaction
*/
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
try {
em.getTransaction().begin();
/*
* Delete record.
*/
- DroolsPdpEntity droolsPdpEntity = em.find(DroolsPdpEntity.class, pdpId);
+ var droolsPdpEntity = em.find(DroolsPdpEntity.class, pdpId);
if (droolsPdpEntity != null) {
logger.debug("deletePdp: Removing PDP");
em.remove(droolsPdpEntity);
*
*/
public PmStandbyStateChangeNotifier() {
- int pdpUpdateInterval =
+ var pdpUpdateInterval =
Integer.parseInt(ActiveStandbyProperties.getProperty(ActiveStandbyProperties.PDP_UPDATE_INTERVAL));
isWaitingForActivation = false;
startTimeWaitingForActivationMs = currentTime.getMillis();
* ============LICENSE_START=======================================================
* feature-controller-logging
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 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.drools.system.PolicyController;
import org.onap.policy.drools.system.PolicyControllerConstants;
import org.onap.policy.drools.system.PolicyEngine;
-import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
@Override
public boolean beforeOffer(PolicyController controller, CommInfrastructure protocol, String topic, String event) {
- Logger controllerLogger = LoggerFactory.getLogger(controller.getName());
+ var controllerLogger = LoggerFactory.getLogger(controller.getName());
controllerLogger.info("[IN|{}|{}]{}{}", protocol, topic, LINE_SEP, event);
return false;
}
public boolean afterDeliver(DroolsController controller, TopicSink sink, Object fact, String json,
boolean success) {
if (success) {
- Logger controllerLogger = LoggerFactory
+ var controllerLogger = LoggerFactory
.getLogger(PolicyControllerConstants.getFactory().get(controller).getName());
controllerLogger.info("[OUT|{}|{}]{}{}", sink.getTopicCommInfrastructure(), sink.getTopic(),
LINE_SEP, json);
public boolean afterOnTopicEvent(PolicyEngine engine, PdpdConfiguration configuration, CommInfrastructure commType,
String topic, String event) {
for (ControllerConfiguration controller : configuration.getControllers()) {
- Logger controllerLogger = LoggerFactory.getLogger(controller.getName());
+ var controllerLogger = LoggerFactory.getLogger(controller.getName());
controllerLogger.info("[IN|{}|{}]{}{}", commType, topic, LINE_SEP, event);
}
return false;
import java.sql.Connection;
import java.sql.PreparedStatement;
-import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLTransientException;
import java.util.HashSet;
* @throws Exception exception
*/
protected BasicDataSource makeDataSource() throws Exception {
- Properties props = new Properties();
+ var props = new Properties();
props.put("driverClassName", featProps.getDbDriver());
props.put("url", featProps.getDbUrl());
props.put("username", featProps.getDbUser());
private void deleteExpiredDbLocks() {
logger.info("deleting all expired locks from the DB");
- try (Connection conn = dataSource.getConnection();
- PreparedStatement stmt = conn
- .prepareStatement("DELETE FROM pooling.locks WHERE expirationTime <= now()")) {
+ try (var conn = dataSource.getConnection();
+ var stmt = conn.prepareStatement("DELETE FROM pooling.locks WHERE expirationTime <= now()")) {
int ndel = stmt.executeUpdate();
logger.info("deleted {} expired locks from the DB", ndel);
*/
// @formatter:off
- try (Connection conn = dataSource.getConnection();
+ try (var conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(
"SELECT resourceId FROM pooling.locks WHERE host=? AND owner=? AND expirationTime > now()")) {
// @formatter:on
stmt.setString(1, pdpName);
stmt.setString(2, uuidString);
- try (ResultSet resultSet = stmt.executeQuery()) {
+ try (var resultSet = stmt.executeQuery()) {
while (resultSet.next()) {
- String resourceId = resultSet.getString(1);
+ var resourceId = resultSet.getString(1);
// we have now seen this resource id
expiredIds.remove(resourceId);
return false;
}
- AtomicBoolean result = new AtomicBoolean(false);
+ var result = new AtomicBoolean(false);
feature.resource2lock.computeIfPresent(getResourceId(), (resourceId, curlock) -> {
if (curlock == this && !isUnavailable()) {
return;
}
- AtomicBoolean success = new AtomicBoolean(false);
+ var success = new AtomicBoolean(false);
feature.resource2lock.computeIfPresent(getResourceId(), (resourceId, curlock) -> {
if (curlock == this && !isUnavailable()) {
*/
logger.debug("doLock {}", this);
- try (Connection conn = feature.dataSource.getConnection()) {
- boolean success = false;
+ try (var conn = feature.dataSource.getConnection()) {
+ var success = false;
try {
success = doDbInsert(conn);
*/
private void doUnlock() throws SQLException {
logger.debug("unlock {}", this);
- try (Connection conn = feature.dataSource.getConnection()) {
+ try (var conn = feature.dataSource.getConnection()) {
doDbDelete(conn);
}
*/
logger.debug("doExtend {}", this);
- try (Connection conn = feature.dataSource.getConnection()) {
+ try (var conn = feature.dataSource.getConnection()) {
/*
* invoker may have called extend() before free() had a chance to insert
* the record, thus we have to try to insert, if the update fails
*/
protected boolean doDbInsert(Connection conn) throws SQLException {
logger.debug("insert lock record {}", this);
- try (PreparedStatement stmt =
- conn.prepareStatement("INSERT INTO pooling.locks (resourceId, host, owner, expirationTime) "
+ try (var stmt = conn.prepareStatement("INSERT INTO pooling.locks (resourceId, host, owner, expirationTime) "
+ "values (?, ?, ?, timestampadd(second, ?, now()))")) {
stmt.setString(1, getResourceId());
*/
protected boolean doDbUpdate(Connection conn) throws SQLException {
logger.debug("update lock record {}", this);
- try (PreparedStatement stmt =
- conn.prepareStatement("UPDATE pooling.locks SET resourceId=?, host=?, owner=?,"
+ try (var stmt = conn.prepareStatement("UPDATE pooling.locks SET resourceId=?, host=?, owner=?,"
+ " expirationTime=timestampadd(second, ?, now()) WHERE resourceId=?"
+ " AND ((host=? AND owner=?) OR expirationTime < now())")) {
*/
protected void doDbDelete(Connection conn) throws SQLException {
logger.debug("delete lock record {}", this);
- try (PreparedStatement stmt = conn
+ try (var stmt = conn
.prepareStatement("DELETE FROM pooling.locks WHERE resourceId=? AND host=? AND owner=?")) {
stmt.setString(1, getResourceId());
* ============LICENSE_START=======================================================
* feature-drools-init
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 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 java.io.Serializable;
import java.util.concurrent.TimeUnit;
-import org.kie.api.runtime.rule.FactHandle;
import org.onap.policy.drools.core.PolicySession;
import org.onap.policy.drools.core.PolicySessionFeatureApi;
import org.onap.policy.drools.system.PolicyEngineConstants;
*/
public Init(final PolicySession policySession) {
// insert this instance into Drools memory
- final FactHandle factHandle = policySession.getKieSession().insert(this);
+ final var factHandle = policySession.getKieSession().insert(this);
// after 10 minutes, remove the object from Drools memory (if needed)
PolicyEngineConstants.getManager().getExecutorService().schedule(() -> {
* ============LICENSE_START=======================================================
* feature-eelf
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 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.eelf;
import com.att.eelf.configuration.Configuration;
-import java.nio.file.Path;
import java.nio.file.Paths;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
String logback = System.getProperty(LoggerUtil.LOGBACK_CONFIGURATION_FILE_SYSTEM_PROPERTY,
LoggerUtil.LOGBACK_CONFIGURATION_FILE_DEFAULT);
- Path logbackPath = Paths.get(logback);
+ var logbackPath = Paths.get(logback);
if (System.getProperty(Configuration.PROPERTY_LOGGING_FILE_PATH) == null) {
System.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH,
logbackPath.getFileName().toString());
}
- Logger logger = FlexLogger.getLogger(this.getClass(), true);
+ var logger = FlexLogger.getLogger(this.getClass(), true);
if (logger.isInfoEnabled()) {
logProperty(logger, LoggerUtil.LOGBACK_CONFIGURATION_FILE_SYSTEM_PROPERTY);
*/
@Override
public Reports healthCheck() {
- Reports reports = new Reports();
+ var reports = new Reports();
boolean thisEngineIsAlive = getEngineManager().isAlive();
reports.setHealthy(thisEngineIsAlive);
- HealthCheck.Report engineReport = new Report();
+ var engineReport = new Report();
engineReport.setHealthy(thisEngineIsAlive);
engineReport.setName("PDP-D");
engineReport.setUrl("self");
reports.getDetails().add(engineReport);
for (HttpClient client : clients) {
- HealthCheck.Report report = new Report();
+ var report = new Report();
report.setName(client.getName());
report.setUrl(client.getBaseUrl());
report.setHealthy(true);
try {
- Response response = client.get();
+ var response = client.get();
report.setCode(response.getStatus());
if (report.getCode() != 200) {
report.setHealthy(false);
@Getter
protected TopicSinkClient client;
- @Getter
- protected final String name = PolicyEngineConstants.PDP_NAME;
-
protected LifecycleState state = new LifecycleStateTerminated(this);
@GsonJsonIgnore
stats.setPdpInstanceId(PolicyEngineConstants.PDP_NAME);
}
+ public String getName() {
+ return PolicyEngineConstants.PDP_NAME;
+ }
+
@GsonJsonIgnore
public DomainMaker getDomainMaker() {
return PolicyEngineConstants.getManager().getDomainMaker();
protected PdpStatus statusPayload(@NonNull PdpState state) {
var status = new PdpStatus();
- status.setName(name);
+ status.setName(getName());
status.setPdpGroup(group);
status.setPdpSubgroup(subGroup);
status.setState(state);
import org.apache.commons.lang3.tuple.Pair;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.drools.domain.models.artifact.NativeArtifactPolicy;
-import org.onap.policy.drools.policies.DomainMaker;
import org.onap.policy.models.pdp.concepts.PdpResponseDetails;
import org.onap.policy.models.pdp.concepts.PdpStateChange;
import org.onap.policy.models.pdp.concepts.PdpUpdate;
protected List<ToscaPolicy> syncPolicies(List<ToscaPolicy> policies,
BiPredicate<PolicyTypeController, ToscaPolicy> sync) {
List<ToscaPolicy> failedPolicies = new ArrayList<>();
- DomainMaker domain = fsm.getDomainMaker();
+ var domain = fsm.getDomainMaker();
for (ToscaPolicy policy : policies) {
ToscaConceptIdentifier policyType = policy.getTypeIdentifier();
PolicyTypeController controller = fsm.getController(policyType);
}
protected PdpResponseDetails response(String requestId, PdpResponseStatus responseStatus, String message) {
- PdpResponseDetails response = new PdpResponseDetails();
+ var response = new PdpResponseDetails();
response.setResponseTo(requestId);
response.setResponseStatus(responseStatus);
if (message != null) {
private boolean perform(ToscaPolicy policy, Predicate<PolicyController> operation) {
try {
List<PolicyController> selected = selectControllers(policy);
- boolean success = true;
+ var success = true;
for (PolicyController controller : selected) {
success = modifyController(operation, controller) && success;
}
PolicyController controller;
try {
nativePolicy = fsm.getDomainMaker().convertTo(policy, NativeArtifactPolicy.class);
- DroolsConfiguration droolsConfig =
+ var droolsConfig =
new DroolsConfiguration(
nativePolicy.getProperties().getRulesArtifact().getArtifactId(),
nativePolicy.getProperties().getRulesArtifact().getGroupId(),
public boolean undeploy(ToscaPolicy policy) {
try {
NativeArtifactPolicy nativePolicy = fsm.getDomainMaker().convertTo(policy, NativeArtifactPolicy.class);
- DroolsConfiguration noConfig =
+ var noConfig =
new DroolsConfiguration(
DroolsControllerConstants.NO_ARTIFACT_ID,
DroolsControllerConstants.NO_GROUP_ID,
}
private boolean update(NativeArtifactPolicy nativePolicy, DroolsConfiguration droolsConfig) {
- ControllerConfiguration controllerConfig =
+ var controllerConfig =
new ControllerConfiguration(nativePolicy.getProperties().getController().getName(),
ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UPDATE, droolsConfig);
return PolicyEngineConstants.getManager().updatePolicyController(controllerConfig) != null;
@Override
public Lock createLock(String resourceId, String ownerKey, int holdSec,
LockCallback callback, boolean waitForLock) {
- AlwaysSuccessLock successLock = new AlwaysSuccessLock(resourceId, ownerKey, holdSec, callback);
+ var successLock = new AlwaysSuccessLock(resourceId, ownerKey, holdSec, callback);
successLock.notifyAvailable();
return successLock;
}
String name = controller.getName();
- SpecProperties specProps = new SpecProperties(PoolingProperties.PREFIX, name, featProps);
+ var specProps = new SpecProperties(PoolingProperties.PREFIX, name, featProps);
if (FeatureEnabledChecker.isFeatureEnabled(specProps, PoolingProperties.FEATURE_ENABLED)) {
try {
// get & validate the properties
- PoolingProperties props = new PoolingProperties(name, featProps);
+ var props = new PoolingProperties(name, featProps);
logger.info("pooling enabled for {}", name);
ctlr2pool.computeIfAbsent(name, xxx -> makeManager(host, controller, props, activeLatch));
import com.google.gson.JsonParseException;
import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
msg.checkValidity();
- Method meth = current.getClass().getMethod("process", msg.getClass());
+ var meth = current.getClass().getMethod("process", msg.getClass());
changeState((State) meth.invoke(current, msg));
} catch (JsonParseException e) {
throw new PoolingFeatureException("too many hosts in message bucket assignments");
}
- for (int x = 0; x < hostArray.length; ++x) {
+ for (var x = 0; x < hostArray.length; ++x) {
if (hostArray[x] == null) {
throw new PoolingFeatureException("bucket " + x + " has no assignment");
}
@Override
public int hashCode() {
- final int prime = 31;
- int result = 1;
+ final var prime = 31;
+ var result = 1;
result = prime * result + Arrays.hashCode(hostArray);
return result;
}
* Generates a heart beat for this host and its successor.
*/
private void genHeartbeat() {
- Heartbeat msg = makeHeartbeat(System.currentTimeMillis());
+ var msg = makeHeartbeat(System.currentTimeMillis());
publish(getHost(), msg);
if (succHost != null) {
throw new IllegalArgumentException(newLeader + " cannot replace " + alive.first());
}
- Leader msg = makeLeader(alive);
+ var msg = makeLeader(alive);
logger.info("{}/{} hosts have an assignment", msg.getAssignments().getAllHosts().size(), alive.size());
publish(msg);
return new String[BucketAssignments.MAX_BUCKETS];
}
- String[] newArray = new String[oldArray.length];
+ var newArray = new String[oldArray.length];
System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
return newArray;
private void addIndicesToHostBuckets(String[] bucket2host, Map<String, HostBucket> host2data) {
LinkedList<Integer> nullBuckets = new LinkedList<>();
- for (int x = 0; x < bucket2host.length; ++x) {
+ for (var x = 0; x < bucket2host.length; ++x) {
String host = bucket2host[x];
if (host == null) {
nullBuckets.add(x);
super.start();
- Heartbeat hb = makeHeartbeat(hbTimestampMs);
+ var hb = makeHeartbeat(hbTimestampMs);
publish(getHost(), hb);
/*
@Override
public DroolsSession get(String sessName) {
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
DroolsSessionEntity entity = null;
- try (EntityMgrTrans trans = new EntityMgrTrans(em)) {
+ try (var trans = new EntityMgrTrans(em)) {
entity = em.find(DroolsSessionEntity.class, sessName);
if (entity != null) {
logger.info("replace: Entering and manually updating session name= {}", sessName);
- EntityManager em = emf.createEntityManager();
+ var em = emf.createEntityManager();
- try (EntityMgrTrans trans = new EntityMgrTrans(em)) {
+ try (var trans = new EntityMgrTrans(em)) {
if (!update(em, sess)) {
add(em, sess);
private void add(EntityManager em, DroolsSession sess) {
logger.info("add: Inserting session id={}", sess.getSessionId());
- DroolsSessionEntity ent = new DroolsSessionEntity(sess.getSessionName(), sess.getSessionId());
+ var ent = new DroolsSessionEntity(sess.getSessionName(), sess.getSessionId());
em.persist(ent);
}
// create connection to DB
phase = "creating connection";
logger.debug("DbAudit: Creating connection to {}", url);
- try (Connection connection = DriverManager.getConnection(url, user, password)) {
+ try (var connection = DriverManager.getConnection(url, user, password)) {
// create audit table, if needed
if (doCreate) {
// insert an entry into the table
phase = "insert entry";
- String key = UUID.randomUUID().toString();
+ var key = UUID.randomUUID().toString();
insertEntry(connection, key);
phase = "fetch entry";
* ============LICENSE_START=======================================================
* feature-state-management
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
* Modifications Copyright (C) 2021 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
// request.
synchronized (IntegrityMonitorRestManager.class) {
// will include messages associated with subsystem failures
- StringBuilder body = new StringBuilder();
+ var body = new StringBuilder();
// 200=SUCCESS, 500=failure
- int responseValue = 200;
+ var responseValue = 200;
if (im == null) {
try {
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
-import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.AllArgsConstructor;
import lombok.Getter;
*/
private static TreeSet<Integer> countAdditionalNexusRepos() {
TreeSet<Integer> returnIndices = new TreeSet<>();
- Properties properties = StateManagementProperties.getProperties();
+ var properties = StateManagementProperties.getProperties();
Set<String> propertyNames = properties.stringPropertyNames();
for (String currName : propertyNames) {
- Matcher matcher = repoPattern.matcher(currName);
+ var matcher = repoPattern.matcher(currName);
if (matcher.matches()) {
- int currRepoNum = Integer.parseInt(matcher.group(2));
+ var currRepoNum = Integer.parseInt(matcher.group(2));
if (propertyNames.contains(matcher.group(1) + ".audit.url")) {
returnIndices.add(currRepoNum);
}
public void invoke(Properties properties) throws IntegrityMonitorException {
logger.debug("Running 'RepositoryAudit.invoke'");
- InvokeData data = new InvokeData();
+ var data = new InvokeData();
logger.debug("RepositoryAudit.invoke: repoAuditIsActive = {}" + ", repoAuditIgnoreErrors = {}",
data.repoAuditIsActive, data.repoAuditIgnoreErrors);
*/
// output file = ${dir}/out (this supports step '4a')
- File output = data.dir.resolve("out").toFile();
+ var output = data.dir.resolve("out").toFile();
// invoke process, and wait for response
int rval = data.runMaven(output);
}
public void initTimeout() {
- String timeoutString = getProperty("audit.timeout", true);
+ var timeoutString = getProperty("audit.timeout", true);
if (timeoutString != null && !timeoutString.isEmpty()) {
try {
timeoutInSeconds = Long.valueOf(timeoutString);
}
// create text file to write
- try (FileOutputStream fos = new FileOutputStream(dir.resolve("repository-audit.txt").toFile())) {
+ try (var fos = new FileOutputStream(dir.resolve("repository-audit.txt").toFile())) {
fos.write(version.getBytes());
}
artifacts.add(new Artifact("org.apache.maven/maven-embedder/3.2.2"));
- StringBuilder sb = new StringBuilder();
+ var sb = new StringBuilder();
sb.append(
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n"
+ " </execution>\n" + " </executions>\n" + " </plugin>\n"
+ " </plugins>\n" + " </build>\n" + "</project>\n");
- try (FileOutputStream fos = new FileOutputStream(pom.toFile())) {
+ try (var fos = new FileOutputStream(pom.toFile())) {
fos.write(sb.toString().getBytes());
}
}
private void generateDownloadLogs(File output) throws IOException {
// place output in 'fileContents' (replacing the Return characters
// with Newline)
- byte[] outputData = new byte[(int) output.length()];
+ var outputData = new byte[(int) output.length()];
String fileContents;
- try (FileInputStream fis = new FileInputStream(output)) {
+ try (var fis = new FileInputStream(output)) {
//
// Ideally this should be in a loop or even better use
// Java 8 nio functionality.
// generate log messages from 'Downloading' and 'Downloaded'
// messages within the 'mvn' output
- int index = 0;
+ var index = 0;
while ((index = fileContents.indexOf("\nDown", index)) > 0) {
index += 5;
if (fileContents.regionMatches(index, "loading: ", 0, 9)) {
*/
static int runProcess(long timeoutInSeconds, File directory, File stdout, String... command)
throws IOException, InterruptedException {
- ProcessBuilder pb = new ProcessBuilder(command);
+ var pb = new ProcessBuilder(command);
if (directory != null) {
pb.directory(directory);
}
pb.redirectOutput(stdout);
}
- Process process = pb.start();
+ var process = pb.start();
if (process.waitFor(timeoutInSeconds, TimeUnit.SECONDS)) {
// process terminated before the timeout
return process.exitValue();
* ============LICENSE_START=======================================================
* feature-state-management
* ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 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.statemanagement;
import java.io.IOException;
-import java.util.Properties;
import org.onap.policy.common.im.AllSeemsWellException;
import org.onap.policy.common.im.IntegrityMonitorException;
import org.onap.policy.common.im.StateChangeNotifier;
private static void initializeProperties(String configDir) {
//Get the state management properties
try {
- Properties props =
- PropertyUtil.getProperties(configDir + "/feature-state-management.properties");
+ var props = PropertyUtil.getProperties(configDir + "/feature-state-management.properties");
StateManagementProperties.initProperties(props);
logger.info("initializeProperties: resourceName= {}",
StateManagementProperties.getProperty(StateManagementProperties.NODE_NAME));
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 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.
@Override
public String toString() {
- final StringBuilder builder = new StringBuilder();
+ final var builder = new StringBuilder();
builder.append("TTControllerTask [controller=");
builder.append(this.controller);
builder.append(", alive=");
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.onap.policy.drools.stats.PolicyStatsManager;
import org.onap.policy.drools.system.internal.SimpleLockManager;
import org.onap.policy.drools.utils.PropertyUtil;
-import org.onap.policy.drools.utils.logging.LoggerUtil;
import org.onap.policy.drools.utils.logging.MdcTransaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* ============LICENSE_START=======================================================
* ONAP
* ================================================================================
- * Copyright (C) 2017-2019,2021 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 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 lombok.AccessLevel;
import lombok.NoArgsConstructor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* Loger Utils.
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class LoggerUtil {
- private static final Logger LOGGER = LoggerFactory.getLogger(LoggerUtil.class);
-
/**
* Logback configuration file system property.
*/
public static final String LOGBACK_CONFIGURATION_FILE_DEFAULT = "config/logback.xml";
}
-