* ============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.
/**
* logger.
*/
- private static Logger logger = LoggerFactory.getLogger(MavenDroolsController.class);
+ private static Logger logger = LoggerFactory.getLogger(IndexedDroolsControllerFactory.class);
/**
* Policy Controller Name Index.
* ============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.
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;
}
}
+ /*
+ * 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 <T> boolean offer(T event) {
+ public <T> boolean offer(T event) { // NOSONAR
logger.debug("{}: OFFER event", this);
if (this.locked || !this.alive || this.policyContainer.getPolicySessions().isEmpty()) {
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(),
}
}
} 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;
* ============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.
@Override
public void shutdown() {
- return;
+ // do nothing
}
@Override
public void halt() {
- return;
+ // do nothing
}
@Override
this.backupController(name);
}
} catch (Exception e) {
- logger.info("{}: no existing {} properties {}", this, name, e);
+ logger.info("{}: no existing {} properties", this, name, e);
// continue
}
}
* ============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.
}
}
- if (present) {
- return;
- } else {
+ if (!present) {
logger.info("{}: adding coder set for {}: {} ", this, reverseKey, coderTools);
toolsets.add(coderTools);
}
* ============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.
* 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 ";
/**
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);
}
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);
}
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);
}
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);
}
}
* ============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");
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;
*/
protected final List<CoderFilters> coders = new CopyOnWriteArrayList<>();
- /**
- * Tree model (instead of class model) generic parsing to be able to inspect elements.
- */
- protected JsonParser filteringParser = new JsonParser();
-
/**
* custom coder.
*/
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();
}
}
* ============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.
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
*/
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;
/* 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;
/**
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;
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<PotentialCoderFilter> 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;
* ============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.
*/
public void set(String name, Object value) {
if (!declaredProperty(name, value)) {
- getAdditionalProperties().put(name, (Object) value);
+ getAdditionalProperties().put(name, value);
}
}
*/
public ControllerConfiguration with(String name, Object value) {
if (!declaredProperty(name, value)) {
- getAdditionalProperties().put(name, (Object) value);
+ getAdditionalProperties().put(name, value);
}
return this;
}
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();
}
*/
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.
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;
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);
}
/* 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())
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 =
e);
}
}
-
- PolicyEngineConstants.getManager().open();
}
}
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);
}
}
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;
}
} 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 {
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;
}
}
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;
}
}
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;
/**
* Policy Drools Controller.
*/
- private volatile DroolsController droolsController;
+ private final AtomicReference<DroolsController> droolsController = new AtomicReference<>();
/**
* Properties used to initialize controller.
}
return droolsController
+ .get()
.getBaseDomainNames()
.stream()
.map(d -> new ToscaPolicyTypeIdentifier(d,
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);
}
}
*/
@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())
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;
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);
this.alive = true;
}
- final boolean success = this.droolsController.start();
+ final boolean success = this.droolsController.get().start();
// register for events
source.unregister(this);
}
- boolean success = this.droolsController.stop();
+ boolean success = this.droolsController.get().stop();
FeatureApiUtils.apply(getProviders(),
feature -> feature.afterStop(this),
this.stop();
- getDroolsFactory().shutdown(this.droolsController);
+ getDroolsFactory().shutdown(this.droolsController.get());
FeatureApiUtils.apply(getProviders(),
feature -> feature.afterShutdown(this),
}
this.stop();
- getDroolsFactory().destroy(this.droolsController);
+ getDroolsFactory().destroy(this.droolsController.get());
getPersistenceManager().deleteController(this.name);
FeatureApiUtils.apply(getProviders(),
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),
return true;
}
- boolean success = this.droolsController.offer(event);
+ boolean success = this.droolsController.get().offer(event);
FeatureApiUtils.apply(getProviders(),
feature -> feature.afterOffer(this, event, success),
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),
// 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),
this.locked = false;
}
- boolean success = this.droolsController.unlock();
+ boolean success = this.droolsController.get().unlock();
FeatureApiUtils.apply(getProviders(),
feature -> feature.afterUnlock(this),
*/
@Override
public DroolsController getDrools() {
- return this.droolsController;
+ return this.droolsController.get();
}
* ============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.
}
}
- /**
- * 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.
*
* ============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.
}
@Override
- public boolean free() {
+ public synchronized boolean free() {
if (!freeAllowed()) {
return false;
}
package org.onap.policy.drools.controller.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
}
};
- drools.updateToVersion(GROUP, ARTIFACT, VERSION2, null, null);
+ assertThatCode(() -> drools.updateToVersion(GROUP, ARTIFACT, VERSION2, null, null)).doesNotThrowAnyException();
}
@Test
package org.onap.policy.drools.controller.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
+
import org.junit.Assert;
import org.junit.Test;
import org.onap.policy.common.utils.gson.GsonTestUtils;
@Test
public void testSerialize() {
- new GsonTestUtils().compareGson(new NullDroolsController(), NullDroolsControllerTest.class);
+ assertThatCode(() -> new GsonTestUtils().compareGson(new NullDroolsController(),
+ NullDroolsControllerTest.class)).doesNotThrowAnyException();
}
@Test
@Test
public void getGroupId() {
- Assert.assertEquals(new NullDroolsController().getGroupId(), DroolsControllerConstants.NO_GROUP_ID);
+ Assert.assertEquals(DroolsControllerConstants.NO_GROUP_ID, new NullDroolsController().getGroupId());
}
@Test
public void getArtifactId() {
- Assert.assertEquals(new NullDroolsController().getArtifactId(), DroolsControllerConstants.NO_ARTIFACT_ID);
+ Assert.assertEquals(DroolsControllerConstants.NO_ARTIFACT_ID, new NullDroolsController().getArtifactId());
}
@Test
public void getVersion() {
- Assert.assertEquals(new NullDroolsController().getVersion(), DroolsControllerConstants.NO_VERSION);
+ Assert.assertEquals(DroolsControllerConstants.NO_VERSION, new NullDroolsController().getVersion());
}
@Test
* ============LICENSE_START=======================================================
* Configuration Test
* ================================================================================
- * 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.
controllerConfig2.setOperation(OPERATION2);
controllerConfig2.setDrools(DROOLS_CONFIG2);
- assertEquals(controllerConfig2.getName(), NAME2);
- assertEquals(controllerConfig2.getOperation(), OPERATION2);
- assertEquals(controllerConfig2.getDrools(), DROOLS_CONFIG2);
+ assertEquals(NAME2, controllerConfig2.getName());
+ assertEquals(OPERATION2, controllerConfig2.getOperation());
+ assertEquals(DROOLS_CONFIG2, controllerConfig2.getDrools());
assertEquals(controllerConfig2, controllerConfig2.withName(NAME2));
assertEquals(controllerConfig2, controllerConfig2.withOperation(OPERATION2));
assertFalse(controllerConfig2.declaredProperty("dummy", NAME));
- assertEquals(controllerConfig2.declaredPropertyOrNotFound(NAME, NAME2), NAME2);
- assertEquals(controllerConfig2.declaredPropertyOrNotFound(OPERATION, OPERATION2), OPERATION2);
- assertEquals(controllerConfig2.declaredPropertyOrNotFound(DROOLS_STRING, DROOLS_CONFIG2), DROOLS_CONFIG2);
- assertEquals(controllerConfig2.declaredPropertyOrNotFound("dummy", NAME), NAME);
+ assertEquals(NAME2, controllerConfig2.declaredPropertyOrNotFound(NAME, NAME2));
+ assertEquals(OPERATION2, controllerConfig2.declaredPropertyOrNotFound(OPERATION, OPERATION2));
+ assertEquals(DROOLS_CONFIG2, controllerConfig2.declaredPropertyOrNotFound(DROOLS_STRING, DROOLS_CONFIG2));
+ assertEquals(NAME, controllerConfig2.declaredPropertyOrNotFound("dummy", NAME));
int hashCode = new HashCodeBuilder().append(NAME2).append(OPERATION2).append(DROOLS_CONFIG2)
.append(additionalProperties).toHashCode();
* ============LICENSE_START=======================================================
* Configuration Test
* ================================================================================
- * 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.
assertTrue(droolsConfig.equals(droolsConfig));
droolsConfig.set(ARTIFACT_ID_STRING, "foobar");
- assertEquals(droolsConfig.get(ARTIFACT_ID_STRING), "foobar");
+ assertEquals("foobar", droolsConfig.get(ARTIFACT_ID_STRING));
assertEquals(droolsConfig.with(ARTIFACT_ID_STRING, "foobar2"), droolsConfig);
droolsConfig2.setGroupId(GROUPID2);
droolsConfig2.setVersion(VERSION2);
- assertEquals(droolsConfig2.getArtifactId(), ARTIFACT2);
- assertEquals(droolsConfig2.getGroupId(), GROUPID2);
- assertEquals(droolsConfig2.getVersion(), VERSION2);
+ assertEquals(ARTIFACT2, droolsConfig2.getArtifactId());
+ assertEquals(GROUPID2, droolsConfig2.getGroupId());
+ assertEquals(VERSION2, droolsConfig2.getVersion());
assertEquals(droolsConfig2.withArtifactId(ARTIFACT2), droolsConfig2);
assertEquals(droolsConfig2.withGroupId(GROUPID2), droolsConfig2);
assertTrue(droolsConfig2.declaredProperty(VERSION_STRING, VERSION2));
assertFalse(droolsConfig2.declaredProperty("dummy", NAME));
- assertEquals(droolsConfig2.declaredPropertyOrNotFound(ARTIFACT_ID_STRING, ARTIFACT2),
- ARTIFACT2);
- assertEquals(droolsConfig2.declaredPropertyOrNotFound(GROUP_ID_STRING, GROUPID2), GROUPID2);
- assertEquals(droolsConfig2.declaredPropertyOrNotFound(VERSION_STRING, VERSION2), VERSION2);
- assertEquals(droolsConfig2.declaredPropertyOrNotFound("dummy", ARTIFACT2), ARTIFACT2);
+ assertEquals(ARTIFACT2, droolsConfig2.declaredPropertyOrNotFound(ARTIFACT_ID_STRING, ARTIFACT2));
+ assertEquals(GROUPID2, droolsConfig2.declaredPropertyOrNotFound(GROUP_ID_STRING, GROUPID2));
+ assertEquals(VERSION2, droolsConfig2.declaredPropertyOrNotFound(VERSION_STRING, VERSION2));
+ assertEquals(ARTIFACT2, droolsConfig2.declaredPropertyOrNotFound("dummy", ARTIFACT2));
final int hashCode = new HashCodeBuilder().append(ARTIFACT2).append(GROUPID2).append(VERSION2)
.append(additionalProperties).toHashCode();
* ============LICENSE_START=======================================================
* Configuration Test
* ================================================================================
- * 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.
//
// Test get additional properties
//
- assertEquals(drools.getAdditionalProperties().size(), 1);
+ assertEquals(1, drools.getAdditionalProperties().size());
//
// Test Not found
//
// Test additional properties
//
- assertEquals(controller.getAdditionalProperties().size(), 1);
+ assertEquals(1, controller.getAdditionalProperties().size());
//
// Not found
// Test additional properties
//
- assertEquals(config.getAdditionalProperties().size(), 1);
+ assertEquals(1, config.getAdditionalProperties().size());
//
// Test NOT FOUND
@Test
public void testConstructor() {
PdpdConfiguration config = new PdpdConfiguration(REQUEST_ID, ENTITY, null);
- assertEquals(config.getRequestId(), REQUEST_ID);
- assertEquals(config.getEntity(), ENTITY);
+ assertEquals(REQUEST_ID, config.getRequestId());
+ assertEquals(ENTITY, config.getEntity());
}
@Test
package org.onap.policy.drools.system;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
public void testSerialize() {
mgr.configure(properties);
- gson.compareGson(mgr, PolicyEngineManagerTest.class);
+ assertThatCode(() -> gson.compareGson(mgr, PolicyEngineManagerTest.class)).doesNotThrowAnyException();
}
@Test
PolicyEngineConstants.getManager().stop();
await().atMost(10, TimeUnit.SECONDS).until(() -> !PolicyEngineConstants.getManager().isAlive());
+ assertFalse(PolicyEngineConstants.getManager().isAlive());
}
}
package org.onap.policy.drools.system.internal;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
import org.onap.policy.common.endpoints.event.comm.TopicSink;
import org.onap.policy.common.endpoints.event.comm.TopicSource;
+import org.onap.policy.common.utils.gson.GsonTestUtils;
import org.onap.policy.drools.controller.DroolsController;
import org.onap.policy.drools.controller.DroolsControllerFactory;
import org.onap.policy.drools.features.PolicyControllerFeatureApi;
@Test
public void testSerialize() {
- new GsonMgmtTestBuilder().addDroolsControllerMock().addTopicSinkMock().addTopicSourceMock().build()
- .compareGson(apc, AggregatedPolicyControllerTest.class);
+ GsonTestUtils gson = new GsonMgmtTestBuilder().addDroolsControllerMock().addTopicSinkMock().addTopicSourceMock()
+ .build();
+ assertThatCode(() -> gson.compareGson(apc, AggregatedPolicyControllerTest.class)).doesNotThrowAnyException();
}
@Test
package org.onap.policy.drools.system.internal;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
MyLockStdSession lock = new MyLockStdSession(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);
// this should invoke the real policy session without throwing an exception
- lock.grant();
+ assertThatCode(() -> lock.grant()).doesNotThrowAnyException();
}
@Test
package org.onap.policy.drools.system.internal;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
feature.createLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false);
// should shut down thread pool
- feature.stop();
+ assertThatCode(() -> feature.stop()).doesNotThrowAnyException();
}
@Test