From 19663843f4fc612f73df8ba970800f2f1a5166a2 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Tue, 7 Apr 2020 09:18:12 -0400 Subject: Address sonar issues in policy-management Addressed the following sonar issues: - modified code to specify the correct class name in the getLogger() call - use equals() instead of "==" for string comparison - remove deprecated code - use ',' instead of "," in indexOf - remove code that is commented out; typically bogus, so the comment was adjusted to satisfy sonar - missing assert in junits - use "{}" instead of concatenation when using logger - either log or rethrow - put arguments for assertEquals() in the correct order - remove "return" statements from the end of void methods - don't always return the same value; just disabled sonar as refactoring would have obfuscated the code - cognitive complexity; used eclipse auto-refactoring to extract out chunks of code into separate methods - don't pass array of classes to class.getDeclaredMethod(); use ellided arguments instead - fix argument count in logger calls - remove unnecessary casts - don't use "volatile" - make methods "synchronized" to match parent class definitions Issue-ID: POLICY-2305 Change-Id: Ie96418f696da4ae6c2ca8d4a914371469e695419 Signed-off-by: Jim Hahn --- .../controller/IndexedDroolsControllerFactory.java | 4 +- .../controller/internal/MavenDroolsController.java | 18 +++-- .../controller/internal/NullDroolsController.java | 6 +- .../drools/persistence/FileSystemPersistence.java | 2 +- .../protocol/coders/GenericEventProtocolCoder.java | 6 +- .../protocol/coders/GsonProtocolCoderToolset.java | 22 +++--- .../protocol/coders/ProtocolCoderToolset.java | 11 +-- .../coders/TopicCoderFilterConfiguration.java | 82 +++++++++++----------- .../configuration/ControllerConfiguration.java | 6 +- .../policy/drools/server/restful/RestManager.java | 2 +- .../system/IndexedPolicyControllerFactory.java | 2 +- .../java/org/onap/policy/drools/system/Main.java | 62 ++++++++-------- .../policy/drools/system/PolicyEngineManager.java | 13 ++-- .../internal/AggregatedPolicyController.java | 48 +++++++------ .../drools/system/internal/FeatureLockImpl.java | 9 +-- .../drools/system/internal/SimpleLockManager.java | 4 +- 16 files changed, 147 insertions(+), 150 deletions(-) (limited to 'policy-management/src/main/java') diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/IndexedDroolsControllerFactory.java b/policy-management/src/main/java/org/onap/policy/drools/controller/IndexedDroolsControllerFactory.java index e5128bb5..6d42ba53 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/IndexedDroolsControllerFactory.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/IndexedDroolsControllerFactory.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 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. @@ -48,7 +48,7 @@ class IndexedDroolsControllerFactory implements DroolsControllerFactory { /** * logger. */ - private static Logger logger = LoggerFactory.getLogger(MavenDroolsController.class); + private static Logger logger = LoggerFactory.getLogger(IndexedDroolsControllerFactory.class); /** * Policy Controller Name Index. diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java index 9b832b04..4e4fddf9 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 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. @@ -195,9 +195,8 @@ public class MavenDroolsController implements DroolsController { if (newGroupId.equalsIgnoreCase(this.getGroupId()) && newArtifactId.equalsIgnoreCase(this.getArtifactId()) - && newVersion.equalsIgnoreCase(this.getVersion())) { - logger.warn("All in the right version: " + newGroupId + ":" - + newArtifactId + ":" + newVersion + " vs. " + this); + && newVersion.equalsIgnoreCase(this.getVersion())) { + logger.warn("All in the right version: {}:{}:{} vs. {}", newGroupId, newArtifactId, newVersion, this); return; } @@ -516,8 +515,13 @@ public class MavenDroolsController implements DroolsController { } + /* + * This method always returns "true", which causes a sonar complaint. However, + * refactoring or restructuring it would unnecessarily complicate it, thus we'll just + * disable the sonar complaint. + */ @Override - public boolean offer(T event) { + public boolean offer(T event) { // NOSONAR logger.debug("{}: OFFER event", this); if (this.locked || !this.alive || this.policyContainer.getPolicySessions().isEmpty()) { @@ -541,7 +545,7 @@ public class MavenDroolsController implements DroolsController { boolean successInject = this.policyContainer.insertAll(event); if (!successInject) { - logger.warn(this + "Failed to inject into PolicyContainer {}", this.getSessionNames()); + logger.warn("{} Failed to inject into PolicyContainer {}", this, this.getSessionNames()); } FeatureApiUtils.apply(getDroolsProviders().getList(), @@ -687,7 +691,7 @@ public class MavenDroolsController implements DroolsController { } } } catch (Exception e) { - logger.warn("Can't retrieve CORE sessions: " + e.getMessage(), e); + logger.warn("Can't retrieve CORE sessions", e); sessionNames.add(e.getMessage()); } return sessionNames; diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java index a43a1467..4373b35e 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 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. @@ -49,12 +49,12 @@ public class NullDroolsController implements DroolsController { @Override public void shutdown() { - return; + // do nothing } @Override public void halt() { - return; + // do nothing } @Override diff --git a/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java b/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java index 1347eb6c..ab19a898 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java +++ b/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java @@ -364,7 +364,7 @@ public class FileSystemPersistence implements SystemPersistence { this.backupController(name); } } catch (Exception e) { - logger.info("{}: no existing {} properties {}", this, name, e); + logger.info("{}: no existing {} properties", this, name, e); // continue } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GenericEventProtocolCoder.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GenericEventProtocolCoder.java index cb4ce07e..b16186d6 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GenericEventProtocolCoder.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GenericEventProtocolCoder.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 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. @@ -150,9 +150,7 @@ abstract class GenericEventProtocolCoder { } } - if (present) { - return; - } else { + if (!present) { logger.info("{}: adding coder set for {}: {} ", this, reverseKey, coderTools); toolsets.add(coderTools); } diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GsonProtocolCoderToolset.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GsonProtocolCoderToolset.java index ff154fb5..51b28d66 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GsonProtocolCoderToolset.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/GsonProtocolCoderToolset.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 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. @@ -46,6 +46,7 @@ import org.slf4j.LoggerFactory; * Tools used for encoding/decoding using GSON. */ class GsonProtocolCoderToolset extends ProtocolCoderToolset { + private static final String CANNOT_FETCH_CLASS = "{}: cannot fetch application class {}"; private static final String FETCH_CLASS_EX_MSG = "cannot fetch application class "; /** @@ -174,13 +175,12 @@ class GsonProtocolCoderToolset extends ProtocolCoderToolset { try { decoderClass = droolsController.fetchModelClass(decoderFilter.getCodedClass()); if (decoderClass == null) { - logger.warn("{}: cannot fetch application class {}", this, decoderFilter.getCodedClass()); + logger.warn(CANNOT_FETCH_CLASS, this, decoderFilter.getCodedClass()); throw new IllegalStateException( FETCH_CLASS_EX_MSG + decoderFilter.getCodedClass()); } } catch (final Exception e) { - logger.warn("{}: cannot fetch application class {} because of {}", this, - decoderFilter.getCodedClass(), e.getMessage()); + logger.warn(CANNOT_FETCH_CLASS, this, decoderFilter.getCodedClass()); throw new UnsupportedOperationException( FETCH_CLASS_EX_MSG + decoderFilter.getCodedClass(), e); } @@ -192,11 +192,10 @@ class GsonProtocolCoderToolset extends ProtocolCoderToolset { final Field gsonField = gsonClassContainer.getField(this.customCoder.staticCoderField); final Object gsonObject = gsonField.get(null); final Method fromJsonMethod = gsonObject.getClass().getDeclaredMethod("fromJson", - new Class[] {String.class, Class.class}); + String.class, Class.class); return fromJsonMethod.invoke(gsonObject, json, decoderClass); } catch (final Exception e) { - logger.warn("{}: cannot fetch application class {} because of {}", this, - decoderFilter.getCodedClass(), e.getMessage()); + logger.warn(CANNOT_FETCH_CLASS, this, decoderFilter.getCodedClass()); throw new UnsupportedOperationException( FETCH_CLASS_EX_MSG + decoderFilter.getCodedClass(), e); } @@ -204,8 +203,7 @@ class GsonProtocolCoderToolset extends ProtocolCoderToolset { try { return this.decoder.fromJson(json, decoderClass); } catch (final Exception e) { - logger.warn("{} cannot decode {} into {} because of {}", this, json, decoderClass.getName(), - e.getMessage(), e); + logger.warn("{} cannot decode {} into {}", this, json, decoderClass.getName()); throw new UnsupportedOperationException( "cannont decode into " + decoderFilter.getCodedClass(), e); } @@ -227,17 +225,17 @@ class GsonProtocolCoderToolset extends ProtocolCoderToolset { final Field gsonField = gsonClassContainer.getField(this.customCoder.staticCoderField); final Object gsonObject = gsonField.get(null); final Method toJsonMethod = - gsonObject.getClass().getDeclaredMethod("toJson", new Class[] {Object.class}); + gsonObject.getClass().getDeclaredMethod("toJson", Object.class); return (String) toJsonMethod.invoke(gsonObject, event); } catch (final Exception e) { - logger.warn("{} cannot custom-encode {} because of {}", this, event, e.getMessage(), e); + logger.warn("{} cannot custom-encode {}", this, event); throw new UnsupportedOperationException("event cannot be encoded", e); } } else { try { return this.encoder.toJson(event); } catch (final Exception e) { - logger.warn("{} cannot encode {} because of {}", this, event, e.getMessage(), e); + logger.warn("{} cannot encode {}", this, event); throw new UnsupportedOperationException("event cannot be encoded", e); } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolset.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolset.java index a4add9ce..8f99f0dd 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolset.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolset.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 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"); @@ -21,7 +21,6 @@ package org.onap.policy.drools.protocol.coders; -import com.google.gson.JsonParser; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -65,11 +64,6 @@ public abstract class ProtocolCoderToolset { */ protected final List coders = new CopyOnWriteArrayList<>(); - /** - * Tree model (instead of class model) generic parsing to be able to inspect elements. - */ - protected JsonParser filteringParser = new JsonParser(); - /** * custom coder. */ @@ -287,8 +281,7 @@ public abstract class ProtocolCoderToolset { builder.append("ProtocolCoderToolset [topic=").append(this.topic).append(", controllerId=") .append(this.controllerId).append(", groupId=").append(this.groupId).append(", artifactId=") .append(this.artifactId).append(", coders=").append(this.coders) - .append(", filteringParser=").append(this.filteringParser).append(", customCoder=") - .append(this.customCoder).append("]"); + .append(", customCoder=").append(this.customCoder).append("]"); return builder.toString(); } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/TopicCoderFilterConfiguration.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/TopicCoderFilterConfiguration.java index 35a49a1d..2d694530 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/TopicCoderFilterConfiguration.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/TopicCoderFilterConfiguration.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * policy-management * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 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. @@ -44,23 +44,23 @@ public class TopicCoderFilterConfiguration { public CustomCoder(String rawCustomCoder) { if (rawCustomCoder != null && !rawCustomCoder.isEmpty()) { - this.className = rawCustomCoder.substring(0, rawCustomCoder.indexOf(",")); + this.className = rawCustomCoder.substring(0, rawCustomCoder.indexOf(',')); if (this.className == null || this.className.isEmpty()) { throw new IllegalArgumentException( "No classname to create CustomCoder cannot be created"); } - this.staticCoderField = rawCustomCoder.substring(rawCustomCoder.indexOf(",") + 1); + this.staticCoderField = rawCustomCoder.substring(rawCustomCoder.indexOf(',') + 1); if (this.staticCoderField == null || this.staticCoderField.isEmpty()) { throw new IllegalArgumentException( "No staticCoderField to create CustomCoder cannot be created for class " + className); } } } - + /** * Constructor. - * + * * @param className class name * @param staticCoderField static coder field */ @@ -78,37 +78,37 @@ public class TopicCoderFilterConfiguration { this.staticCoderField = staticCoderField; } - /** + /** * Get class container. - * - * @return the className + * + * @return the className **/ public String getClassContainer() { return className; } - /** + /** * Set class container. - * - * @param className the className to set + * + * @param className the className to set **/ public void setClassContainer(String className) { this.className = className; } - /** + /** * Get static coder field. - * - * @return the staticCoderField + * + * @return the staticCoderField **/ public String getStaticCoderField() { return staticCoderField; } - /** + /** * Set static coder field. - * - * @param staticCoderField the staticGson to set + * + * @param staticCoderField the staticGson to set **/ public void setStaticCoderField(String staticCoderField) { this.staticCoderField = staticCoderField; @@ -154,7 +154,7 @@ public class TopicCoderFilterConfiguration { /* decoder class (pending from being able to be fetched and found in some class loader) */ protected String codedClass; - /* filters to apply to the selection of the decodedClass; */ + /* filters to apply to the selection of the decodedClass */ protected JsonProtocolFilter filter; /** @@ -168,36 +168,36 @@ public class TopicCoderFilterConfiguration { this.filter = filter; } - /** + /** * Get coded class. - * - * @return the decodedClass + * + * @return the decodedClass **/ public String getCodedClass() { return codedClass; } /** Set coded class. - * - * @param decodedClass the decodedClass to set + * + * @param decodedClass the decodedClass to set **/ public void setCodedClass(String decodedClass) { this.codedClass = decodedClass; } - /** + /** * Get filter. - * - * @return the filter + * + * @return the filter **/ public JsonProtocolFilter getFilter() { return filter; } - /** + /** * Set filter. - * - * @param filter the filter to set + * + * @param filter the filter to set **/ public void setFilter(JsonProtocolFilter filter) { this.filter = filter; @@ -241,35 +241,35 @@ public class TopicCoderFilterConfiguration { this.customGsonCoder = customGsonCoder; } - /** + /** * Get topic. - * @return the topic + * @return the topic **/ public String getTopic() { return topic; } /** Get coder filters. - * - * @return the decoderFilters + * + * @return the decoderFilters **/ public List getCoderFilters() { return coderFilters; } - /** + /** * Get custom gson coder. - * - * @return the customGsonCoder + * + * @return the customGsonCoder **/ public CustomGsonCoder getCustomGsonCoder() { return customGsonCoder; } - /** + /** * Set custom gson coder. - * - * @param customGsonCoder the customGsonCoder to set + * + * @param customGsonCoder the customGsonCoder to set **/ public void setCustomGsonCoder(CustomGsonCoder customGsonCoder) { this.customGsonCoder = customGsonCoder; diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/ControllerConfiguration.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/ControllerConfiguration.java index d6df0e42..d6504c38 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/ControllerConfiguration.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/ControllerConfiguration.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-management * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 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. @@ -260,7 +260,7 @@ public class ControllerConfiguration { */ public void set(String name, Object value) { if (!declaredProperty(name, value)) { - getAdditionalProperties().put(name, (Object) value); + getAdditionalProperties().put(name, value); } } @@ -273,7 +273,7 @@ public class ControllerConfiguration { */ public ControllerConfiguration with(String name, Object value) { if (!declaredProperty(name, value)) { - getAdditionalProperties().put(name, (Object) value); + getAdditionalProperties().put(name, value); } return this; } diff --git a/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java b/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java index c6d5e02d..db280a1f 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java +++ b/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java @@ -704,7 +704,7 @@ public class RestManager { required = true) ControllerConfiguration controllerConfiguration) { if (controllerName == null || controllerName.isEmpty() || controllerConfiguration == null - || controllerConfiguration.getName().intern() != controllerName) { + || !controllerName.equals(controllerConfiguration.getName())) { return Response.status(Response.Status.BAD_REQUEST) .entity("A valid or matching controller names must be provided").build(); } diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/IndexedPolicyControllerFactory.java b/policy-management/src/main/java/org/onap/policy/drools/system/IndexedPolicyControllerFactory.java index 528f1e0d..cb526e04 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/IndexedPolicyControllerFactory.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/IndexedPolicyControllerFactory.java @@ -40,7 +40,7 @@ import org.slf4j.LoggerFactory; */ class IndexedPolicyControllerFactory implements PolicyControllerFactory { // get an instance of logger - private static final Logger logger = LoggerFactory.getLogger(PolicyControllerFactory.class); + private static final Logger logger = LoggerFactory.getLogger(IndexedPolicyControllerFactory.class); /** * Policy Controller Name Index. diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/Main.java b/policy-management/src/main/java/org/onap/policy/drools/system/Main.java index ea687e03..cd3cc102 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/Main.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/Main.java @@ -27,7 +27,6 @@ import org.onap.policy.common.endpoints.http.client.HttpClientConfigException; import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; import org.onap.policy.common.utils.security.CryptoUtils; -import org.onap.policy.drools.persistence.SystemPersistence; import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.utils.PropertyUtil; @@ -57,54 +56,33 @@ public class Main { public static void main(String[] args) { /* start logger */ - Logger logger = LoggerFactory.getLogger(Main.class); /* system properties */ - - for (Properties systemProperties : SystemPersistenceConstants.getManager().getSystemProperties()) { - if (!StringUtils.isBlank(systemProperties.getProperty(SYSTEM_SYMM_KEY))) { - PropertyUtil.setDefaultCryptoCoder(new CryptoUtils(systemProperties.getProperty(SYSTEM_SYMM_KEY))); - } - PropertyUtil.setSystemProperties(systemProperties); - } + setSystemProperties(); /* 0. boot */ - PolicyEngineConstants.getManager().boot(args); /* 1.a. Configure Engine */ - - Properties engineProperties; - try { - engineProperties = SystemPersistenceConstants.getManager().getEngineProperties(); - } catch (IllegalArgumentException iae) { - logger.warn("Main: engine properties not found. Using default configuration.", iae); - engineProperties = PolicyEngineConstants.getManager().defaultTelemetryConfig(); - } - - PolicyEngineConstants.getManager().configure(engineProperties); + configureEngine(logger); /* 1.b. Load Installation Environment(s) */ - for (Properties env : SystemPersistenceConstants.getManager().getEnvironmentProperties()) { PolicyEngineConstants.getManager().setEnvironment(env); } /* 2.a Add topics */ - for (Properties topicProperties : SystemPersistenceConstants.getManager().getTopicProperties()) { TopicEndpointManager.getManager().addTopics(topicProperties); } /* 2.b Add HTTP Servers */ - for (Properties serverProperties : SystemPersistenceConstants.getManager().getHttpServerProperties()) { HttpServletServerFactoryInstance.getServerFactory().build(serverProperties); } /* 2.c Add HTTP Clients */ - for (Properties clientProperties : SystemPersistenceConstants.getManager().getHttpClientProperties()) { try { HttpClientFactoryInstance.getClientFactory().build(clientProperties); @@ -114,7 +92,36 @@ public class Main { } /* 3. Start the Engine with the basic services only (no Policy Controllers) */ + MdcTransaction trans = startEngineOnly(logger); + + /* 4. Create and start the controllers */ + createAndStartControllers(logger, trans); + + PolicyEngineConstants.getManager().open(); + } + + private static void setSystemProperties() { + for (Properties systemProperties : SystemPersistenceConstants.getManager().getSystemProperties()) { + if (!StringUtils.isBlank(systemProperties.getProperty(SYSTEM_SYMM_KEY))) { + PropertyUtil.setDefaultCryptoCoder(new CryptoUtils(systemProperties.getProperty(SYSTEM_SYMM_KEY))); + } + PropertyUtil.setSystemProperties(systemProperties); + } + } + + private static void configureEngine(Logger logger) { + Properties engineProperties; + try { + engineProperties = SystemPersistenceConstants.getManager().getEngineProperties(); + } catch (IllegalArgumentException iae) { + logger.warn("Main: engine properties not found. Using default configuration.", iae); + engineProperties = PolicyEngineConstants.getManager().defaultTelemetryConfig(); + } + PolicyEngineConstants.getManager().configure(engineProperties); + } + + private static MdcTransaction startEngineOnly(Logger logger) { MdcTransaction trans = MdcTransaction.newTransaction(null, null) .setServiceName(Main.class.getSimpleName()) @@ -157,9 +164,10 @@ public class Main { e); System.exit(1); } + return trans; + } - /* 4. Create and start the controllers */ - + private static void createAndStartControllers(Logger logger, MdcTransaction trans) { for (final Properties controllerProperties : SystemPersistenceConstants.getManager().getControllerProperties()) { final String controllerName = @@ -205,7 +213,5 @@ public class Main { e); } } - - PolicyEngineConstants.getManager().open(); } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.java b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.java index 95ee88cb..5ab06b37 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.java @@ -484,10 +484,10 @@ class PolicyEngineManager implements PolicyEngine { return policyController; } catch (final Exception e) { - logger.error("{}: cannot update-policy-controller because of {}", this, e.getMessage(), e); + logger.error("{}: cannot update-policy-controller", this); throw e; } catch (final LinkageError e) { - logger.error("{}: cannot update-policy-controllers (rules) because of {}", this, e.getMessage(), e); + logger.error("{}: cannot update-policy-controllers (rules)", this); throw new IllegalStateException(e); } } @@ -498,7 +498,7 @@ class PolicyEngineManager implements PolicyEngine { policyController = getControllerFactory().get(controllerName); } catch (final IllegalArgumentException e) { // not found - logger.warn("Policy Controller " + controllerName + " not found", e); + logger.warn("Policy Controller {} not found", controllerName, e); } return policyController; } @@ -875,6 +875,7 @@ class PolicyEngineManager implements PolicyEngine { } catch (final InterruptedException e) { synchronized (PolicyEngineManager.this) { /* courtesy to shutdown() to allow it to return */ + Thread.currentThread().interrupt(); } logger.info("{}: finishing a graceful shutdown ", PolicyEngineManager.this, e); } finally { @@ -1204,8 +1205,7 @@ class PolicyEngineManager implements PolicyEngine { return this.deliver(busType, topic, json); } catch (final Exception e) { - logger.warn("{}: cannot deliver {} over {}:{} because of {}", this, event, busType, topic, e.getMessage(), - e); + logger.warn("{}: cannot deliver {} over {}:{}", this, event, busType, topic); throw e; } } @@ -1239,8 +1239,7 @@ class PolicyEngineManager implements PolicyEngine { return sink.send(event); } catch (final Exception e) { - logger.warn("{}: cannot deliver {} over {}:{} because of {}", this, event, busType, topic, e.getMessage(), - e); + logger.warn("{}: cannot deliver {} over {}:{}", this, event, busType, topic); throw e; } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java b/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java index 0c12dbcb..8eb2f85b 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java @@ -26,6 +26,7 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Properties; +import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import org.onap.policy.common.endpoints.event.comm.Topic; import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; @@ -101,7 +102,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen /** * Policy Drools Controller. */ - private volatile DroolsController droolsController; + private final AtomicReference droolsController = new AtomicReference<>(); /** * Properties used to initialize controller. @@ -154,6 +155,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen } return droolsController + .get() .getBaseDomainNames() .stream() .map(d -> new ToscaPolicyTypeIdentifier(d, @@ -191,9 +193,9 @@ public class AggregatedPolicyController implements PolicyController, TopicListen private void initDrools(Properties properties) { try { // Register with drools infrastructure - this.droolsController = getDroolsFactory().build(properties, sources, sinks); + this.droolsController.set(getDroolsFactory().build(properties, sources, sinks)); } catch (Exception | LinkageError e) { - logger.error("{}: cannot init-drools because of {}", this, e.getMessage(), e); + logger.error("{}: cannot init-drools", this); throw new IllegalArgumentException(e); } } @@ -215,8 +217,9 @@ public class AggregatedPolicyController implements PolicyController, TopicListen */ @Override public boolean updateDrools(DroolsConfiguration newDroolsConfiguration) { - DroolsConfiguration oldDroolsConfiguration = new DroolsConfiguration(this.droolsController.getArtifactId(), - this.droolsController.getGroupId(), this.droolsController.getVersion()); + DroolsController controller = this.droolsController.get(); + DroolsConfiguration oldDroolsConfiguration = new DroolsConfiguration(controller.getArtifactId(), + controller.getGroupId(), controller.getVersion()); if (oldDroolsConfiguration.getGroupId().equalsIgnoreCase(newDroolsConfiguration.getGroupId()) && oldDroolsConfiguration.getArtifactId().equalsIgnoreCase(newDroolsConfiguration.getArtifactId()) @@ -233,11 +236,11 @@ public class AggregatedPolicyController implements PolicyController, TopicListen return true; } - if (droolsController.isBrained() + if (controller.isBrained() && (newDroolsConfiguration.getArtifactId() == null || DroolsControllerConstants.NO_ARTIFACT_ID.equals(newDroolsConfiguration.getArtifactId()))) { // detach maven artifact - DroolsControllerConstants.getFactory().destroy(this.droolsController); + DroolsControllerConstants.getFactory().destroy(controller); } boolean success = true; @@ -250,16 +253,19 @@ public class AggregatedPolicyController implements PolicyController, TopicListen this.initDrools(this.properties); + // have a new controller now - get it + controller = this.droolsController.get(); + if (isLocked()) { - droolsController.lock(); + controller.lock(); } else { - droolsController.unlock(); + controller.unlock(); } if (isAlive()) { - droolsController.start(); + controller.start(); } else { - droolsController.stop(); + controller.stop(); } } catch (RuntimeException e) { logger.error("{}: cannot update-drools because of {}", this, e.getMessage(), e); @@ -309,7 +315,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen this.alive = true; } - final boolean success = this.droolsController.start(); + final boolean success = this.droolsController.get().start(); // register for events @@ -363,7 +369,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen source.unregister(this); } - boolean success = this.droolsController.stop(); + boolean success = this.droolsController.get().stop(); FeatureApiUtils.apply(getProviders(), feature -> feature.afterStop(this), @@ -389,7 +395,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen this.stop(); - getDroolsFactory().shutdown(this.droolsController); + getDroolsFactory().shutdown(this.droolsController.get()); FeatureApiUtils.apply(getProviders(), feature -> feature.afterShutdown(this), @@ -412,7 +418,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen } this.stop(); - getDroolsFactory().destroy(this.droolsController); + getDroolsFactory().destroy(this.droolsController.get()); getPersistenceManager().deleteController(this.name); FeatureApiUtils.apply(getProviders(), @@ -439,7 +445,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen return; } - boolean success = this.droolsController.offer(topic, event); + boolean success = this.droolsController.get().offer(topic, event); FeatureApiUtils.apply(getProviders(), feature -> feature.afterOffer(this, commType, topic, event, success), @@ -462,7 +468,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen return true; } - boolean success = this.droolsController.offer(event); + boolean success = this.droolsController.get().offer(event); FeatureApiUtils.apply(getProviders(), feature -> feature.afterOffer(this, event, success), @@ -513,7 +519,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen throw new IllegalArgumentException("Unsupported topic " + topic + " for delivery"); } - boolean success = this.droolsController.deliver(this.topic2Sinks.get(topic), event); + boolean success = this.droolsController.get().deliver(this.topic2Sinks.get(topic), event); FeatureApiUtils.apply(getProviders(), feature -> feature.afterDeliver(this, commType, topic, event, success), @@ -556,7 +562,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen // it does not affect associated sources/sinks, they are // autonomous entities - boolean success = this.droolsController.lock(); + boolean success = this.droolsController.get().lock(); FeatureApiUtils.apply(getProviders(), feature -> feature.afterLock(this), @@ -589,7 +595,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen this.locked = false; } - boolean success = this.droolsController.unlock(); + boolean success = this.droolsController.get().unlock(); FeatureApiUtils.apply(getProviders(), feature -> feature.afterUnlock(this), @@ -628,7 +634,7 @@ public class AggregatedPolicyController implements PolicyController, TopicListen */ @Override public DroolsController getDrools() { - return this.droolsController; + return this.droolsController.get(); } diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/internal/FeatureLockImpl.java b/policy-management/src/main/java/org/onap/policy/drools/system/internal/FeatureLockImpl.java index 5690b187..6b0c8a43 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/internal/FeatureLockImpl.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/internal/FeatureLockImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 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. @@ -113,13 +113,6 @@ public abstract class FeatureLockImpl extends LockImpl { } } - /** - * The subclass should make use of {@link #freeAllowed()} in its implementation of - * {@link #free()}. - */ - @Override - public abstract boolean free(); - /** * Determines if the lock can be freed. * diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/internal/SimpleLockManager.java b/policy-management/src/main/java/org/onap/policy/drools/system/internal/SimpleLockManager.java index a62d7667..1df139e2 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/internal/SimpleLockManager.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/internal/SimpleLockManager.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019-2020 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. @@ -227,7 +227,7 @@ public class SimpleLockManager extends LockManager } @Override - public boolean free() { + public synchronized boolean free() { if (!freeAllowed()) { return false; } -- cgit 1.2.3-korg