diff options
27 files changed, 1333 insertions, 62 deletions
diff --git a/models-dao/src/test/java/org/onap/policy/models/dao/DummyTimestampEntity.java b/models-dao/src/test/java/org/onap/policy/models/dao/DummyTimestampEntity.java index d18a91573..0dee8b402 100644 --- a/models-dao/src/test/java/org/onap/policy/models/dao/DummyTimestampEntity.java +++ b/models-dao/src/test/java/org/onap/policy/models/dao/DummyTimestampEntity.java @@ -32,7 +32,6 @@ import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NonNull; -import org.onap.policy.common.utils.validation.Assertions; import org.onap.policy.models.base.PfConcept; import org.onap.policy.models.base.PfKey; import org.onap.policy.models.base.PfTimestampKey; @@ -93,7 +92,6 @@ public class DummyTimestampEntity extends PfConcept { key.clean(); } - @Override public int compareTo(@NonNull final PfConcept otherObj) { if (this == otherObj) { diff --git a/models-interactions/model-actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/AppcActorServiceProvider.java b/models-interactions/model-actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/AppcActorServiceProvider.java index 2491c33a1..1ec46899f 100644 --- a/models-interactions/model-actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/AppcActorServiceProvider.java +++ b/models-interactions/model-actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/AppcActorServiceProvider.java @@ -34,6 +34,7 @@ import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.controlloop.ControlLoopOperation; import org.onap.policy.controlloop.VirtualControlLoopEvent; import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicActor; +import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperator; import org.onap.policy.controlloop.policy.Policy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -74,6 +75,9 @@ public class AppcActorServiceProvider extends BidirectionalTopicActor { */ public AppcActorServiceProvider() { super(NAME); + + addOperator(BidirectionalTopicOperator.makeOperator(NAME, ModifyConfigOperation.NAME, this, + AppcOperation.SELECTOR_KEYS, ModifyConfigOperation::new)); } diff --git a/models-interactions/model-actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/AppcOperation.java b/models-interactions/model-actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/AppcOperation.java new file mode 100644 index 000000000..8bc1a7f32 --- /dev/null +++ b/models-interactions/model-actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/AppcOperation.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.appc; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation; +import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperator; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; +import org.onap.policy.controlloop.actorserviceprovider.topic.SelectorKey; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Superclass for APPC Operations. + */ +public abstract class AppcOperation extends BidirectionalTopicOperation<Request, Response> { + private static final Logger logger = LoggerFactory.getLogger(AppcOperation.class); + private static final StandardCoder coder = new StandardCoder(); + public static final String VNF_ID_KEY = "generic-vnf.vnf-id"; + + /** + * Keys used to match the response with the request listener. The sub request ID is a + * UUID, so it can be used to uniquely identify the response. + * <p/> + * Note: if these change, then {@link #getExpectedKeyValues(int, Request)} must be + * updated accordingly. + */ + public static final List<SelectorKey> SELECTOR_KEYS = List.of(new SelectorKey("CommonHeader", "SubRequestID")); + + /** + * Constructs the object. + * + * @param params operation parameters + * @param operator operator that created this operation + */ + public AppcOperation(ControlLoopOperationParams params, BidirectionalTopicOperator operator) { + super(params, operator, Response.class); + } + + /** + * Makes a request, given the target VNF. This is a support function for + * {@link #makeRequest(int)}. + * + * @param attempt attempt number + * @param targetVnf target VNF + * @return a new request + */ + protected Request makeRequest(int attempt, String targetVnf) { + Request request = new Request(); + request.setCommonHeader(new CommonHeader()); + request.getCommonHeader().setRequestId(params.getRequestId()); + + // TODO ok to use UUID, or does it have to be the "attempt"? + request.getCommonHeader().setSubRequestId(UUID.randomUUID().toString()); + + request.setAction(getName()); + + // convert payload strings to objects + if (params.getPayload() == null) { + logger.info("{}: no payload specified for {}", getFullName(), params.getRequestId()); + } else { + convertPayload(params.getPayload(), request.getPayload()); + } + + // add/replace specific values + request.getPayload().put(VNF_ID_KEY, targetVnf); + + return request; + } + + /** + * Converts a payload. The original value is assumed to be a JSON string, which is + * decoded into an object. + * + * @param source source from which to get the values + * @param target where to place the decoded values + */ + private static void convertPayload(Map<String, String> source, Map<String, Object> target) { + for (Entry<String, String> ent : source.entrySet()) { + try { + target.put(ent.getKey(), coder.decode(ent.getValue(), Object.class)); + + } catch (CoderException e) { + logger.warn("cannot decode JSON value {}: {}", ent.getKey(), ent.getValue(), e); + } + } + } + + /** + * Note: these values must match {@link #SELECTOR_KEYS}. + */ + @Override + protected List<String> getExpectedKeyValues(int attempt, Request request) { + return List.of(request.getCommonHeader().getSubRequestId()); + } + + @Override + protected Status detmStatus(String rawResponse, Response response) { + if (response.getStatus() == null) { + throw new IllegalArgumentException("APP-C response is missing the response status"); + } + + ResponseCode code = ResponseCode.toResponseCode(response.getStatus().getCode()); + if (code == null) { + throw new IllegalArgumentException( + "unknown APPC-C response status code: " + response.getStatus().getCode()); + } + + switch (code) { + case SUCCESS: + return Status.SUCCESS; + case FAILURE: + return Status.FAILURE; + case ERROR: + case REJECT: + throw new IllegalArgumentException("APP-C request was not accepted, code=" + code); + case ACCEPT: + default: + // awaiting a "final" response + return Status.STILL_WAITING; + } + } + + /** + * Sets the message to the status description, if available. + */ + @Override + public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response response) { + if (response.getStatus() == null || response.getStatus().getDescription() == null) { + return setOutcome(outcome, result); + } + + outcome.setResult(result); + outcome.setMessage(response.getStatus().getDescription()); + return outcome; + } +} diff --git a/models-interactions/model-actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/ModifyConfigOperation.java b/models-interactions/model-actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/ModifyConfigOperation.java new file mode 100644 index 000000000..5839df58e --- /dev/null +++ b/models-interactions/model-actors/actor.appc/src/main/java/org/onap/policy/controlloop/actor/appc/ModifyConfigOperation.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.appc; + +import java.util.concurrent.CompletableFuture; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.policy.aai.AaiConstants; +import org.onap.policy.aai.AaiCqResponse; +import org.onap.policy.appc.Request; +import org.onap.policy.controlloop.actor.aai.AaiCustomQueryOperation; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperator; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ModifyConfigOperation extends AppcOperation { + private static final Logger logger = LoggerFactory.getLogger(ModifyConfigOperation.class); + + public static final String NAME = "ModifyConfig"; + + /** + * Constructs the object. + * + * @param params operation parameters + * @param operator operator that created this operation + */ + public ModifyConfigOperation(ControlLoopOperationParams params, BidirectionalTopicOperator operator) { + super(params, operator); + } + + /** + * Ensures that A&AI customer query has been performed, and then runs the guard query. + */ + @Override + @SuppressWarnings("unchecked") + protected CompletableFuture<OperationOutcome> startPreprocessorAsync() { + ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME) + .operation(AaiCustomQueryOperation.NAME).payload(null).retry(null).timeoutSec(null).build(); + + // run Custom Query and Guard, in parallel + return allOf(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams), this::startGuardAsync); + } + + @Override + protected Request makeRequest(int attempt) { + AaiCqResponse cq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY); + + GenericVnf genvnf = cq.getGenericVnfByModelInvariantId(params.getTarget().getResourceID()); + if (genvnf == null) { + logger.info("{}: target entity could not be found for {}", getFullName(), params.getRequestId()); + throw new IllegalArgumentException("target vnf-id could not be found"); + } + + return makeRequest(attempt, genvnf.getVnfId()); + } +} diff --git a/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcOperationTest.java b/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcOperationTest.java new file mode 100644 index 000000000..8a86b346c --- /dev/null +++ b/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcOperationTest.java @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.appc; + +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; + +import java.util.Arrays; +import java.util.Map; +import java.util.TreeMap; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.appc.ResponseStatus; +import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation.Status; +import org.onap.policy.controlloop.policy.PolicyResult; + +public class AppcOperationTest extends BasicAppcOperation { + private AppcOperation oper; + + /** + * Sets up. + */ + @Before + public void setUp() throws Exception { + super.setUp(); + + oper = new AppcOperation(params, operator) { + @Override + protected Request makeRequest(int attempt) { + return oper.makeRequest(attempt, MY_VNF); + } + }; + } + + @Test + public void testAppcOperation() { + assertEquals(DEFAULT_ACTOR, oper.getActorName()); + assertEquals(DEFAULT_OPERATION, oper.getName()); + } + + @Test + public void testMakeRequest() { + Request request = oper.makeRequest(2, MY_VNF); + assertEquals(DEFAULT_OPERATION, request.getAction()); + + assertNotNull(request.getPayload()); + + CommonHeader header = request.getCommonHeader(); + assertNotNull(header); + assertEquals(params.getRequestId(), header.getRequestId()); + + String subreq = header.getSubRequestId(); + assertNotNull(subreq); + + // a subsequent request should have a different sub-request id + assertNotEquals(subreq, oper.makeRequest(2, MY_VNF).getCommonHeader().getSubRequestId()); + + // repeat using a null payload + params = params.toBuilder().payload(null).build(); + oper = new AppcOperation(params, operator) { + @Override + protected Request makeRequest(int attempt) { + return oper.makeRequest(attempt, MY_VNF); + } + }; + assertEquals(Map.of(AppcOperation.VNF_ID_KEY, MY_VNF), oper.makeRequest(2, MY_VNF).getPayload()); + } + + @Test + public void testConvertPayload() { + Request request = oper.makeRequest(2, MY_VNF); + + // @formatter:off + assertEquals( + Map.of(AppcOperation.VNF_ID_KEY, MY_VNF, + KEY1, Map.of("input", "hello"), + KEY2, Map.of("output", "world")), + request.getPayload()); + // @formatter:on + + + /* + * insert invalid json text into the payload. + */ + Map<String, String> payload = new TreeMap<>(params.getPayload()); + payload.put("invalid-key", "{invalid json"); + + params = params.toBuilder().payload(payload).build(); + + oper = new AppcOperation(params, operator) { + @Override + protected Request makeRequest(int attempt) { + return oper.makeRequest(attempt, MY_VNF); + } + }; + request = oper.makeRequest(2, MY_VNF); + + // @formatter:off + assertEquals( + Map.of(AppcOperation.VNF_ID_KEY, MY_VNF, + KEY1, Map.of("input", "hello"), + KEY2, Map.of("output", "world")), + request.getPayload()); + // @formatter:on + } + + @Test + public void testGetExpectedKeyValues() { + Request request = oper.makeRequest(2, MY_VNF); + assertEquals(Arrays.asList(request.getCommonHeader().getSubRequestId()), + oper.getExpectedKeyValues(50, request)); + } + + @Test + public void testDetmStatusStringResponse() { + final ResponseStatus status = response.getStatus(); + + // null status + response.setStatus(null); + assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus("", response)) + .withMessage("APP-C response is missing the response status"); + response.setStatus(status); + + // invalid code + status.setCode(-45); + assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus("", response)) + .withMessage("unknown APPC-C response status code: -45"); + + status.setCode(ResponseCode.SUCCESS.getValue()); + assertEquals(Status.SUCCESS, oper.detmStatus("", response)); + + status.setCode(ResponseCode.FAILURE.getValue()); + assertEquals(Status.FAILURE, oper.detmStatus("", response)); + + status.setCode(ResponseCode.ERROR.getValue()); + assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus("", response)) + .withMessage("APP-C request was not accepted, code=" + ResponseCode.ERROR.getValue()); + + status.setCode(ResponseCode.REJECT.getValue()); + assertThatIllegalArgumentException().isThrownBy(() -> oper.detmStatus("", response)) + .withMessage("APP-C request was not accepted, code=" + ResponseCode.REJECT.getValue()); + + status.setCode(ResponseCode.ACCEPT.getValue()); + assertEquals(Status.STILL_WAITING, oper.detmStatus("", response)); + } + + @Test + public void testSetOutcome() { + final ResponseStatus status = response.getStatus(); + + // null status + response.setStatus(null); + assertSame(outcome, oper.setOutcome(outcome, PolicyResult.SUCCESS, response)); + assertEquals(PolicyResult.SUCCESS, outcome.getResult()); + assertNotNull(outcome.getMessage()); + response.setStatus(status); + + // null description + status.setDescription(null); + assertSame(outcome, oper.setOutcome(outcome, PolicyResult.FAILURE, response)); + assertEquals(PolicyResult.FAILURE, outcome.getResult()); + assertNotNull(outcome.getMessage()); + status.setDescription(MY_DESCRIPTION); + + for (PolicyResult result : PolicyResult.values()) { + assertSame(outcome, oper.setOutcome(outcome, result, response)); + assertEquals(result, outcome.getResult()); + assertEquals(MY_DESCRIPTION, outcome.getMessage()); + } + } +} diff --git a/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java b/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java index 0dfea32d6..305c6d7cd 100644 --- a/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java +++ b/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/AppcServiceProviderTest.java @@ -27,9 +27,10 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.time.Instant; +import java.util.Arrays; import java.util.HashMap; import java.util.UUID; - +import java.util.stream.Collectors; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -128,6 +129,17 @@ public class AppcServiceProviderTest { } @Test + public void testConstructor() { + AppcActorServiceProvider prov = new AppcActorServiceProvider(); + + // verify that it has the operators we expect + var expected = Arrays.asList(ModifyConfigOperation.NAME).stream().sorted().collect(Collectors.toList()); + var actual = prov.getOperationNames().stream().sorted().collect(Collectors.toList()); + + assertEquals(expected.toString(), actual.toString()); + } + + @Test public void testConstructModifyConfigRequest() { policy.setPayload(new HashMap<>()); policy.getPayload().put(KEY1, VALUE1); diff --git a/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/BasicAppcOperation.java b/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/BasicAppcOperation.java new file mode 100644 index 000000000..cbdcad6b0 --- /dev/null +++ b/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/BasicAppcOperation.java @@ -0,0 +1,191 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.appc; + +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; + +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.appc.ResponseStatus; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.coder.StandardCoderObject; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.controlloop.actor.test.BasicBidirectionalTopicOperation; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperator; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.policy.Target; +import org.powermock.reflect.Whitebox; + +/** + * Superclass for various operator tests. + */ +public abstract class BasicAppcOperation extends BasicBidirectionalTopicOperation { + protected static final String MY_DESCRIPTION = "my-description"; + protected static final String MY_VNF = "my-vnf"; + protected static final String KEY1 = "my-key-A"; + protected static final String KEY2 = "my-key-B"; + protected static final String VALUE1 = "{\"input\":\"hello\"}"; + protected static final String VALUE2 = "{\"output\":\"world\"}"; + protected static final String RESOURCE_ID = "my-resource"; + + protected Response response; + + /** + * Constructs the object using a default actor and operation name. + */ + public BasicAppcOperation() { + super(); + } + + /** + * Constructs the object. + * + * @param actor actor name + * @param operation operation name + */ + public BasicAppcOperation(String actor, String operation) { + super(actor, operation); + } + + /** + * Initializes mocks and sets up. + */ + public void setUp() throws Exception { + super.setUp(); + + response = new Response(); + + ResponseStatus status = new ResponseStatus(); + response.setStatus(status); + status.setCode(ResponseCode.SUCCESS.getValue()); + status.setDescription(MY_DESCRIPTION); + } + + /** + * Runs the operation and verifies that the response is successful. + * + * @param operation operation to run + */ + protected void verifyOperation(AppcOperation operation) + throws InterruptedException, ExecutionException, TimeoutException { + + CompletableFuture<OperationOutcome> future2 = operation.start(); + executor.runAll(100); + assertFalse(future2.isDone()); + + verify(forwarder).register(any(), listenerCaptor.capture()); + provideResponse(listenerCaptor.getValue(), ResponseCode.SUCCESS.getValue(), MY_DESCRIPTION); + + executor.runAll(100); + assertTrue(future2.isDone()); + + outcome = future2.get(); + assertEquals(PolicyResult.SUCCESS, outcome.getResult()); + assertEquals(MY_DESCRIPTION, outcome.getMessage()); + } + + /** + * Pretty-prints a request and verifies that the result matches the expected JSON. + * + * @param <T> request type + * @param expectedJsonFile name of the file containing the expected JSON + * @param request request to verify + * @throws CoderException if the request cannot be pretty-printed + */ + protected <T> void verifyRequest(String expectedJsonFile, T request) throws CoderException { + String json = new StandardCoder().encode(request, true); + String expected = ResourceUtils.getResourceAsString(expectedJsonFile); + + // strip request id, because it changes each time + final String stripper = "svc-request-id[^,]*"; + json = json.replaceFirst(stripper, "").trim(); + expected = expected.replaceFirst(stripper, "").trim(); + + assertEquals(expected, json); + } + + /** + * Verifies that an exception is thrown if a field is missing from the enrichment + * data. + * + * @param fieldName name of the field to be removed from the enrichment data + * @param expectedText text expected in the exception message + */ + protected void verifyMissing(String fieldName, String expectedText, + BiFunction<ControlLoopOperationParams, BidirectionalTopicOperator, AppcOperation> maker) { + + makeContext(); + enrichment.remove(fieldName); + + AppcOperation oper = maker.apply(params, operator); + + assertThatIllegalArgumentException().isThrownBy(() -> Whitebox.invokeMethod(oper, "makeRequest", 1)) + .withMessageContaining("missing").withMessageContaining(expectedText); + } + + @Override + protected void makeContext() { + super.makeContext(); + + Target target = new Target(); + target.setResourceID(RESOURCE_ID); + + params = params.toBuilder().target(target).build(); + } + + /** + * Provides a response to the listener. + * + * @param listener listener to which to provide the response + * @param code response code + * @param description response description + */ + protected void provideResponse(BiConsumer<String, StandardCoderObject> listener, int code, String description) { + Response response = new Response(); + + ResponseStatus status = new ResponseStatus(); + response.setStatus(status); + status.setCode(code); + status.setDescription(description); + + provideResponse(listener, Util.translate("", response, String.class)); + } + + @Override + protected Map<String, String> makePayload() { + return Map.of(KEY1, VALUE1, KEY2, VALUE2); + } +} diff --git a/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/ModifyConfigOperationTest.java b/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/ModifyConfigOperationTest.java new file mode 100644 index 000000000..f7c88f67c --- /dev/null +++ b/models-interactions/model-actors/actor.appc/src/test/java/org/onap/policy/controlloop/actor/appc/ModifyConfigOperationTest.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.appc; + +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.policy.aai.AaiCqResponse; +import org.onap.policy.appc.Request; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext; + +public class ModifyConfigOperationTest extends BasicAppcOperation { + + private ModifyConfigOperation oper; + + public ModifyConfigOperationTest() { + super(DEFAULT_ACTOR, ModifyConfigOperation.NAME); + } + + @Before + public void setUp() throws Exception { + super.setUp(); + oper = new ModifyConfigOperation(params, operator); + } + + @Test + public void testModifyConfigOperation() { + assertEquals(DEFAULT_ACTOR, oper.getActorName()); + assertEquals(ModifyConfigOperation.NAME, oper.getName()); + } + + @Test + public void testStartPreprocessorAsync() { + CompletableFuture<OperationOutcome> future = new CompletableFuture<>(); + context = mock(ControlLoopEventContext.class); + when(context.obtain(eq(AaiCqResponse.CONTEXT_KEY), any())).thenReturn(future); + params = params.toBuilder().context(context).build(); + + AtomicBoolean guardStarted = new AtomicBoolean(); + + oper = new ModifyConfigOperation(params, operator) { + @Override + protected CompletableFuture<OperationOutcome> startGuardAsync() { + guardStarted.set(true); + return super.startGuardAsync(); + } + }; + + assertSame(future, oper.startPreprocessorAsync()); + assertFalse(future.isDone()); + assertTrue(guardStarted.get()); + } + + @Test + public void testMakeRequest() { + AaiCqResponse cq = new AaiCqResponse("{}"); + + // missing vnf-id + params.getContext().setProperty(AaiCqResponse.CONTEXT_KEY, cq); + assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest(1)); + + // populate the CQ data with a vnf-id + GenericVnf genvnf = new GenericVnf(); + genvnf.setVnfId(MY_VNF); + genvnf.setModelInvariantId(RESOURCE_ID); + cq.setInventoryResponseItems(Arrays.asList(genvnf)); + + Request request = oper.makeRequest(2); + assertNotNull(request); + assertEquals(MY_VNF, request.getPayload().get(ModifyConfigOperation.VNF_ID_KEY)); + } +} diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatisticsTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatisticsTest.java index 0b22e1b3e..edef2975e 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatisticsTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatisticsTest.java @@ -29,6 +29,7 @@ import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Date; + import org.junit.Test; import org.onap.policy.models.base.PfTimestampKey; import org.onap.policy.models.base.PfValidationResult; @@ -43,11 +44,9 @@ public class JpaPdpStatisticsTest { public void testConstructor() { assertThatThrownBy(() -> new JpaPdpStatistics((PfTimestampKey) null)).hasMessageContaining("key"); - assertThatThrownBy(() -> new JpaPdpStatistics((JpaPdpStatistics) null)) - .hasMessageContaining("copyConcept"); + assertThatThrownBy(() -> new JpaPdpStatistics((JpaPdpStatistics) null)).hasMessageContaining("copyConcept"); - assertThatThrownBy(() -> new JpaPdpStatistics((PdpStatistics) null)) - .hasMessageContaining("authorativeConcept"); + assertThatThrownBy(() -> new JpaPdpStatistics((PdpStatistics) null)).hasMessageContaining("authorativeConcept"); assertNotNull(new JpaPdpStatistics()); assertNotNull(new JpaPdpStatistics(new PfTimestampKey())); diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java index 08c01b68f..3cae650a3 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java @@ -49,8 +49,10 @@ import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.authorative.provider.AuthorativeToscaProvider; import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput; @@ -101,7 +103,7 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { daoParameters.setPersistenceUnit(parameters.getPersistenceUnit()); // Decode the password using Base64 - String decodedPassword = new String(Base64.getDecoder().decode(parameters.getDatabasePassword())); + String decodedPassword = new String(Base64.getDecoder().decode(getValue(parameters.getDatabasePassword()))); // @formatter:off Properties jdbcProperties = new Properties(); @@ -125,6 +127,13 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { } } + private String getValue(final String value) { + if (value != null && value.matches("[$][{].*[}]$")) { + return System.getenv(value.substring(2, value.length() - 1)); + } + return value; + } + @Override public void close() throws PfModelException { LOGGER.debug("closing the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(), @@ -182,6 +191,10 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { public ToscaServiceTemplate deletePolicyType(@NonNull final String name, @NonNull final String version) throws PfModelException { assertInitialized(); + + ToscaPolicyTypeIdentifier policyTypeIdentifier = new ToscaPolicyTypeIdentifier(name, version); + assertPolicyTypeNotSupportedInPdpGroup(policyTypeIdentifier); + return new AuthorativeToscaProvider().deletePolicyType(pfDao, name, version); } @@ -227,6 +240,10 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { public ToscaServiceTemplate deletePolicy(@NonNull final String name, @NonNull final String version) throws PfModelException { assertInitialized(); + + ToscaPolicyIdentifier policyIdentifier = new ToscaPolicyIdentifier(name, version); + assertPolicyNotDeployedInPdpGroup(policyIdentifier); + return new AuthorativeToscaProvider().deletePolicy(pfDao, name, version); } @@ -255,6 +272,10 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId, @NonNull final String policyVersion) throws PfModelException { assertInitialized(); + + assertPolicyNotDeployedInPdpGroup( + new ToscaPolicyIdentifier(policyId, policyVersion + LegacyProvider.LEGACY_MINOR_PATCH_SUFFIX)); + return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId, policyVersion); } @@ -283,6 +304,10 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicy(@NonNull final String policyId, @NonNull final String policyVersion) throws PfModelException { assertInitialized(); + + assertPolicyNotDeployedInPdpGroup( + new ToscaPolicyIdentifier(policyId, policyVersion + LegacyProvider.LEGACY_MINOR_PATCH_SUFFIX)); + return new LegacyProvider().deleteGuardPolicy(pfDao, policyId, policyVersion); } @@ -375,4 +400,42 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); } } + + /** + * Assert that the policy type is not supported in any PDP group. + * + * @param policyTypeIdentifier the policy type identifier + * @throws PfModelException if the policy type is supported in a PDP group + */ + private void assertPolicyTypeNotSupportedInPdpGroup(ToscaPolicyTypeIdentifier policyTypeIdentifier) + throws PfModelException { + for (PdpGroup pdpGroup : getPdpGroups(null)) { + for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) { + if (pdpSubGroup.getSupportedPolicyTypes().contains(policyTypeIdentifier)) { + throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, + "policy type is in use, it is referenced in PDP group " + pdpGroup.getName() + " subgroup " + + pdpSubGroup.getPdpType()); + } + } + } + } + + /** + * Assert that the policy is not deployed in a PDP group. + * + * @param policyIdentifier the identifier of the policy + * @throws PfModelException thrown if the policy is deployed in a PDP group + */ + private void assertPolicyNotDeployedInPdpGroup(final ToscaPolicyIdentifier policyIdentifier) + throws PfModelException { + for (PdpGroup pdpGroup : getPdpGroups(null)) { + for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) { + if (pdpSubGroup.getPolicies().contains(policyIdentifier)) { + throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, + "policy is in use, it is deployed in PDP group " + pdpGroup.getName() + " subgroup " + + pdpSubGroup.getPdpType()); + } + } + } + } } diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java index 3d1c9f61c..c09c6c233 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java @@ -258,7 +258,7 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { @Override public List<PdpStatistics> deletePdpStatistics(final String name, final Date timestamp) { // Not implemented - return null; + return new ArrayList<>(); } /** diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java index aa6802a5a..f085605f8 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java @@ -45,6 +45,7 @@ import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; @@ -536,4 +537,79 @@ public class DatabasePolicyModelsProviderTest { databaseProvider.close(); } + + @Test + public void testDeletePolicyDeployedInSubgroup() throws PfModelException { + List<ToscaPolicyIdentifier> policies = new ArrayList<>(); + + policies.add(new ToscaPolicyIdentifier("p0", "0.0.1")); + policies.add(new ToscaPolicyIdentifier("p1", "0.0.1")); + + List<ToscaPolicyTypeIdentifier> supportedPolicyTypes = new ArrayList<>(); + supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier("pt2", "0.0.1")); + + PdpSubGroup subGroup = new PdpSubGroup(); + subGroup.setPdpType("pdpType"); + subGroup.setSupportedPolicyTypes(supportedPolicyTypes); + subGroup.setPolicies(policies); + + List<PdpSubGroup> pdpSubgroups = new ArrayList<>(); + pdpSubgroups.add(subGroup); + + PdpGroup pdpGroup = new PdpGroup(); + pdpGroup.setName("pdpGroup"); + pdpGroup.setPdpGroupState(PdpState.PASSIVE); + pdpGroup.setPdpSubgroups(pdpSubgroups); + + List<PdpGroup> pdpGroups = new ArrayList<>(); + pdpGroups.add(pdpGroup); + + PolicyModelsProvider databaseProvider = + new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); + + databaseProvider.createPdpGroups(pdpGroups); + + assertThatThrownBy(() -> databaseProvider.deletePolicy("p0", "0.0.1")) + .hasMessageContaining("policy is in use, it is deployed in PDP group pdpGroup subgroup pdpType"); + + assertThatThrownBy(() -> databaseProvider.deletePolicy("p3", "0.0.1")) + .hasMessageContaining("service template not found in database"); + + databaseProvider.close(); + } + + @Test + public void testDeletePolicyTypeSupportedInSubgroup() throws PfModelException { + List<ToscaPolicyTypeIdentifier> supportedPolicyTypes = new ArrayList<>(); + supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier("pt1", "0.0.1")); + supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier("pt2", "0.0.1")); + + PdpSubGroup subGroup = new PdpSubGroup(); + subGroup.setPdpType("pdpType"); + subGroup.setSupportedPolicyTypes(supportedPolicyTypes); + + List<PdpSubGroup> pdpSubgroups = new ArrayList<>(); + pdpSubgroups.add(subGroup); + + PdpGroup pdpGroup = new PdpGroup(); + pdpGroup.setName("pdpGroup"); + pdpGroup.setPdpGroupState(PdpState.PASSIVE); + pdpGroup.setPdpSubgroups(pdpSubgroups); + + List<PdpGroup> pdpGroups = new ArrayList<>(); + pdpGroups.add(pdpGroup); + + PolicyModelsProvider databaseProvider = + new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); + + databaseProvider.createPdpGroups(pdpGroups); + + assertThatThrownBy(() -> databaseProvider.deletePolicyType("pt2", "0.0.1")) + .hasMessageContaining("policy type is in use, it is referenced in PDP group pdpGroup subgroup pdpType"); + + assertThatThrownBy(() -> databaseProvider.deletePolicyType("pt0", "0.0.1")) + .hasMessageContaining("service template not found in database"); + + databaseProvider.close(); + } } diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java index 500d9d4c0..3212428ae 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java @@ -28,6 +28,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; +import java.util.Date; import org.junit.Test; import org.onap.policy.models.pdp.concepts.Pdp; @@ -117,6 +118,12 @@ public class DummyPolicyModelsProviderTest { dummyProvider.updatePdp("name", "type", new Pdp()); dummyProvider.updatePdpStatistics(new ArrayList<>()); assertTrue(dummyProvider.getPdpStatistics("name", null).isEmpty()); + + assertTrue( + dummyProvider.getFilteredPdpStatistics("name", null, null, new Date(), new Date(), null, 0).isEmpty()); + assertTrue(dummyProvider.createPdpStatistics(null).isEmpty()); + assertTrue(dummyProvider.updatePdpStatistics(null).isEmpty()); + assertTrue(dummyProvider.deletePdpStatistics(null, new Date()).isEmpty()); } @Test diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java index 855919e71..de0edef0c 100644 --- a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java @@ -32,10 +32,8 @@ import org.onap.policy.models.pdp.enums.PdpResponseStatus; import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.sim.pdp.PdpSimulatorConstants; import org.onap.policy.models.sim.pdp.parameters.PdpStatusParameters; -import org.onap.policy.models.sim.pdp.parameters.ToscaPolicyTypeIdentifierParameters; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; -import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; /** * This class supports the handling of pdp messages. @@ -64,24 +62,6 @@ public class PdpMessageHandler { } /** - * Method to get supported policy types from the parameters. - * - * @param pdpStatusParameters pdp status parameters - * @return supportedPolicyTypes list of PolicyTypeIdent - */ - private List<ToscaPolicyTypeIdentifier> getSupportedPolicyTypesFromParameters( - final PdpStatusParameters pdpStatusParameters) { - final List<ToscaPolicyTypeIdentifier> supportedPolicyTypes = - new ArrayList<>(pdpStatusParameters.getSupportedPolicyTypes().size()); - for (final ToscaPolicyTypeIdentifierParameters policyTypeIdentParameters : pdpStatusParameters - .getSupportedPolicyTypes()) { - supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(policyTypeIdentParameters.getName(), - policyTypeIdentParameters.getVersion())); - } - return supportedPolicyTypes; - } - - /** * Method to create PdpStatus message from the context, which is to be sent by pdp simulator to pap. * * @return PdpStatus the pdp status message diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider.java index 09cc6c0ca..dc8affc77 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider.java @@ -53,7 +53,7 @@ import org.slf4j.LoggerFactory; public class LegacyProvider { private static final Logger LOGGER = LoggerFactory.getLogger(LegacyProvider.class); - private static final String LEGACY_MINOR_PATCH_SUFFIX = ".0.0"; + public static final String LEGACY_MINOR_PATCH_SUFFIX = ".0.0"; // Recurring constants private static final String NO_POLICY_FOUND_FOR_POLICY = "no policy found for policy: "; diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintValidValues.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintValidValues.java index 2a121573c..664855e42 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintValidValues.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintValidValues.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ package org.onap.policy.models.tosca.simple.concepts; import java.util.ArrayList; import java.util.List; + import javax.persistence.ElementCollection; import lombok.EqualsAndHashCode; @@ -77,8 +78,8 @@ public class JpaToscaConstraintValidValues extends JpaToscaConstraint { @Override public void fromAuthorative(final ToscaConstraint toscaConstraint) { + validValues = new ArrayList<>(); if (toscaConstraint.getValidValues() != null) { - validValues = new ArrayList<>(); validValues.addAll(toscaConstraint.getValidValues()); } } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEntrySchema.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEntrySchema.java index 881d87c4b..b432486ae 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEntrySchema.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaEntrySchema.java @@ -3,7 +3,7 @@ * ONAP Policy Model * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,6 @@ import org.onap.policy.models.base.PfValidationResult.ValidationResult; import org.onap.policy.models.tosca.authorative.concepts.ToscaConstraint; import org.onap.policy.models.tosca.authorative.concepts.ToscaEntrySchema; - /** * Class to represent the EntrySchema of list/map property in TOSCA definition. * @@ -72,7 +71,7 @@ public class JpaToscaEntrySchema private String description; @ElementCollection - private List<JpaToscaConstraint> constraints; + private List<JpaToscaConstraint> constraints = new ArrayList<>(); /** * The full constructor creates a {@link JpaToscaEntrySchema} object with mandatory fields. @@ -170,7 +169,6 @@ public class JpaToscaEntrySchema this.getClass(), ValidationResult.INVALID, "entry schema description may not be blank")); } - if (constraints != null) { for (JpaToscaConstraint constraint : constraints) { if (constraint == null) { diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicy.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicy.java index b500a8bc9..b5da49751 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicy.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicy.java @@ -88,7 +88,7 @@ public class JpaToscaPolicy extends JpaToscaEntityType<ToscaPolicy> implements P @ElementCollection @Lob - private Map<String, String> properties; + private Map<String, String> properties = new LinkedHashMap<>(); @ElementCollection private List<PfConceptKey> targets = new ArrayList<>(); diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaProperty.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaProperty.java index 0e8201f0f..a2127f37c 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaProperty.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaProperty.java @@ -3,7 +3,7 @@ * ONAP Policy Model * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; + import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.EmbeddedId; @@ -35,9 +36,11 @@ import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; + import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NonNull; + import org.apache.commons.lang3.ObjectUtils; import org.onap.policy.models.base.PfAuthorative; import org.onap.policy.models.base.PfConcept; @@ -85,13 +88,13 @@ public class JpaToscaProperty extends PfConcept implements PfAuthorative<ToscaPr private Status status = Status.SUPPORTED; @ElementCollection - private List<JpaToscaConstraint> constraints; + private List<JpaToscaConstraint> constraints = new ArrayList<>(); @Column private JpaToscaEntrySchema entrySchema; @ElementCollection - private Map<String, String> metadata; + private Map<String, String> metadata = new LinkedHashMap<>(); /** * The Default Constructor creates a {@link JpaToscaProperty} object with a null key. diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java index c537bbcb5..a3e18ca41 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java @@ -37,8 +37,10 @@ import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.base.PfValidationResult; import org.onap.policy.models.dao.PfDao; +import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity; import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataTypes; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaEntityType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType; @@ -58,8 +60,11 @@ public class SimpleToscaProvider { private static final Logger LOGGER = LoggerFactory.getLogger(SimpleToscaProvider.class); // Recurring string constants + private static final String DATA_TYPE = "data type "; + private static final String POLICY_TYPE = "policy type "; private static final String SERVICE_TEMPLATE_NOT_FOUND_IN_DATABASE = "service template not found in database"; private static final String DO_NOT_EXIST = " do not exist"; + private static final String NOT_FOUND = " not found"; /** * Get Service Template. @@ -226,7 +231,32 @@ public class SimpleToscaProvider { throws PfModelException { LOGGER.debug("->deleteDataType: key={}", dataTypeKey); - JpaToscaServiceTemplate serviceTemplate = getDataTypes(dao, dataTypeKey.getName(), dataTypeKey.getVersion()); + JpaToscaServiceTemplate serviceTemplate = getServiceTemplate(dao); + + if (!ToscaUtils.doDataTypesExist(serviceTemplate)) { + throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "no data types found"); + } + + JpaToscaDataType dataType4Deletion = serviceTemplate.getDataTypes().get(dataTypeKey); + if (dataType4Deletion == null) { + throw new PfModelRuntimeException(Response.Status.NOT_FOUND, DATA_TYPE + dataTypeKey.getId() + NOT_FOUND); + } + + for (JpaToscaDataType dataType : serviceTemplate.getDataTypes().getAll(null)) { + if (dataType.getReferencedDataTypes().contains(dataTypeKey)) { + throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, DATA_TYPE + dataTypeKey.getId() + + " is in use, it is referenced in data type " + dataType.getId()); + } + } + + if (ToscaUtils.doPolicyTypesExist(serviceTemplate)) { + for (JpaToscaPolicyType policyType : serviceTemplate.getPolicyTypes().getAll(null)) { + if (policyType.getReferencedDataTypes().contains(dataTypeKey)) { + throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, DATA_TYPE + dataTypeKey.getId() + + " is in use, it is referenced in policy type " + policyType.getId()); + } + } + } dao.delete(JpaToscaDataType.class, dataTypeKey); @@ -355,8 +385,37 @@ public class SimpleToscaProvider { throws PfModelException { LOGGER.debug("->deletePolicyType: key={}", policyTypeKey); - JpaToscaServiceTemplate serviceTemplate = - getPolicyTypes(dao, policyTypeKey.getName(), policyTypeKey.getVersion()); + JpaToscaServiceTemplate serviceTemplate = getServiceTemplate(dao); + + if (!ToscaUtils.doPolicyTypesExist(serviceTemplate)) { + throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "no policy types found"); + } + + JpaToscaEntityType<? extends ToscaEntity> policyType4Deletion = + serviceTemplate.getPolicyTypes().get(policyTypeKey); + if (policyType4Deletion == null) { + throw new PfModelRuntimeException(Response.Status.NOT_FOUND, + POLICY_TYPE + policyTypeKey.getId() + NOT_FOUND); + } + + for (JpaToscaPolicyType policyType : serviceTemplate.getPolicyTypes().getAll(null)) { + Collection<JpaToscaEntityType<ToscaEntity>> ancestorList = ToscaUtils + .getEntityTypeAncestors(serviceTemplate.getPolicyTypes(), policyType, new PfValidationResult()); + + if (ancestorList.contains(policyType4Deletion)) { + throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, POLICY_TYPE + policyTypeKey.getId() + + " is in use, it is referenced in policy type " + policyType.getId()); + } + } + + if (ToscaUtils.doPoliciesExist(serviceTemplate)) { + for (JpaToscaPolicy policy : serviceTemplate.getTopologyTemplate().getPolicies().getAll(null)) { + if (policyTypeKey.equals(policy.getType())) { + throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, POLICY_TYPE + + policyTypeKey.getId() + " is in use, it is referenced in policy " + policy.getId()); + } + } + } dao.delete(JpaToscaPolicyType.class, policyTypeKey); @@ -476,7 +535,16 @@ public class SimpleToscaProvider { throws PfModelException { LOGGER.debug("->deletePolicy: key={}", policyKey); - JpaToscaServiceTemplate serviceTemplate = getPolicies(dao, policyKey.getName(), policyKey.getVersion()); + JpaToscaServiceTemplate serviceTemplate = getServiceTemplate(dao); + + if (!ToscaUtils.doPoliciesExist(serviceTemplate)) { + throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "no policies found"); + } + + JpaToscaPolicy policy4Deletion = serviceTemplate.getTopologyTemplate().getPolicies().get(policyKey); + if (policy4Deletion == null) { + throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "policy " + policyKey.getId() + NOT_FOUND); + } dao.delete(JpaToscaPolicy.class, policyKey); @@ -507,7 +575,7 @@ public class SimpleToscaProvider { if (policyType == null) { String errorMessage = - "policy type " + policyTypeKey.getId() + " for policy " + policy.getId() + " does not exist"; + POLICY_TYPE + policyTypeKey.getId() + " for policy " + policy.getId() + " does not exist"; throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, errorMessage); } } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/utils/ToscaUtils.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/utils/ToscaUtils.java index b75273e5e..77633bd27 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/utils/ToscaUtils.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/utils/ToscaUtils.java @@ -211,7 +211,7 @@ public final class ToscaUtils { } /** - * Find all the ancestors of an entity type. + * getLatestPolicyTypeVersion Find all the ancestors of an entity type. * * @param entityTypes the set of entity types that exist * @param entityType the entity type for which to get the parents @@ -227,6 +227,12 @@ public final class ToscaUtils { return CollectionUtils.emptyCollection(); } + if (entityType.getKey().equals(parentEntityTypeKey)) { + result.addValidationMessage(new PfValidationMessage(entityType.getKey(), ToscaUtils.class, + ValidationResult.INVALID, "entity cannot be an ancestor of itself")); + throw new PfModelRuntimeException(Response.Status.CONFLICT, result.toString()); + } + @SuppressWarnings("unchecked") Set<JpaToscaEntityType<ToscaEntity>> ancestorEntitySet = (Set<JpaToscaEntityType<ToscaEntity>>) entityTypes .getAll(parentEntityTypeKey.getName(), parentEntityTypeKey.getVersion()); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapperTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapperTest.java index 62c088c83..332552a73 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapperTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapperTest.java @@ -50,7 +50,13 @@ public class LegacyGuardPolicyMapperTest { JpaToscaPolicy policy = new JpaToscaPolicy(new PfConceptKey("PolicyName", "2.0.0")); serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(policy.getKey(), policy); + policy.setMetadata(null); + assertThatThrownBy(() -> { + new LegacyGuardPolicyMapper().fromToscaServiceTemplate(serviceTemplate); + }).hasMessageContaining("no metadata defined on TOSCA policy"); + policy.setMetadata(new LinkedHashMap<>()); + policy.setProperties(null); assertThatThrownBy(() -> { new LegacyGuardPolicyMapper().fromToscaServiceTemplate(serviceTemplate); }).hasMessageContaining("no properties defined on TOSCA policy"); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java index 4dcfeafc9..79de6f9d9 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java @@ -106,6 +106,7 @@ public class LegacyOperationalPolicyMapperTest { serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().remove(policy1.getKey()); + policy0.setProperties(null); assertThatThrownBy(() -> { new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(serviceTemplate); }).hasMessage("no properties defined on TOSCA policy"); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java index f34c0c869..4937c5cca 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java @@ -36,6 +36,7 @@ import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfReferenceKey; import org.onap.policy.models.dao.DaoParameters; import org.onap.policy.models.dao.PfDao; import org.onap.policy.models.dao.PfDaoFactory; @@ -45,8 +46,10 @@ import org.onap.policy.models.tosca.authorative.provider.AuthorativeToscaProvide import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataTypes; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyTypes; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaProperty; import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate; import org.yaml.snakeyaml.Yaml; @@ -135,13 +138,64 @@ public class SimpleToscaProviderTest { assertEquals(dataType0, gotServiceTemplate.getDataTypes().get(dataType0Key)); assertEquals("Updated Description", gotServiceTemplate.getDataTypes().get(dataType0Key).getDescription()); + assertThatThrownBy(() -> new SimpleToscaProvider().deleteDataType(pfDao, new PfConceptKey("IDontExist:0.0.1"))) + .hasMessage("data type IDontExist:0.0.1 not found"); + JpaToscaServiceTemplate deletedServiceTemplate = new SimpleToscaProvider().deleteDataType(pfDao, dataType0Key); assertEquals(dataType0, deletedServiceTemplate.getDataTypes().get(dataType0Key)); assertEquals("Updated Description", deletedServiceTemplate.getDataTypes().get(dataType0Key).getDescription()); + // Create the data type again + new SimpleToscaProvider().createDataTypes(pfDao, serviceTemplate); + + updatedServiceTemplate.setPolicyTypes(new JpaToscaPolicyTypes()); + JpaToscaPolicyType pt0 = new JpaToscaPolicyType(new PfConceptKey("pt0:0.0.1")); + updatedServiceTemplate.getPolicyTypes().getConceptMap().put(pt0.getKey(), pt0); + new SimpleToscaProvider().createPolicyTypes(pfDao, updatedServiceTemplate); + + deletedServiceTemplate = new SimpleToscaProvider().deleteDataType(pfDao, dataType0Key); + + assertEquals(dataType0, deletedServiceTemplate.getDataTypes().get(dataType0Key)); + assertEquals("Updated Description", deletedServiceTemplate.getDataTypes().get(dataType0Key).getDescription()); + assertThatThrownBy(() -> new SimpleToscaProvider().deleteDataType(pfDao, dataType0Key)) - .hasMessage("data types for DataType0:0.0.1 do not exist"); + .hasMessage("no data types found"); + + // Create the data type again + new SimpleToscaProvider().createDataTypes(pfDao, serviceTemplate); + + JpaToscaPolicyType pt0v2 = new JpaToscaPolicyType(new PfConceptKey("pt0:0.0.2")); + JpaToscaProperty prop0 = new JpaToscaProperty(new PfReferenceKey(pt0v2.getKey(), "prop0")); + prop0.setType(dataType0Key); + pt0v2.getProperties().put(prop0.getKey().getLocalName(), prop0); + updatedServiceTemplate.getPolicyTypes().getConceptMap().put(pt0v2.getKey(), pt0v2); + new SimpleToscaProvider().createPolicyTypes(pfDao, updatedServiceTemplate); + + assertThatThrownBy(() -> new SimpleToscaProvider().deleteDataType(pfDao, dataType0Key)) + .hasMessage("data type DataType0:0.0.1 is in use, it is referenced in policy type pt0:0.0.2"); + + JpaToscaDataType dataType0v2 = new JpaToscaDataType(new PfConceptKey("DataType0:0.0.2")); + updatedServiceTemplate.getDataTypes().getConceptMap().put(dataType0v2.getKey(), dataType0v2); + new SimpleToscaProvider().createDataTypes(pfDao, updatedServiceTemplate); + + deletedServiceTemplate = new SimpleToscaProvider().deleteDataType(pfDao, dataType0v2.getKey()); + + assertEquals(dataType0, deletedServiceTemplate.getDataTypes().get(dataType0Key)); + assertEquals("Updated Description", deletedServiceTemplate.getDataTypes().get(dataType0Key).getDescription()); + + assertThatThrownBy(() -> new SimpleToscaProvider().deleteDataType(pfDao, dataType0Key)) + .hasMessage("data type DataType0:0.0.1 is in use, it is referenced in policy type pt0:0.0.2"); + + JpaToscaDataType dataType1 = new JpaToscaDataType(new PfConceptKey("DataType1:0.0.3")); + JpaToscaProperty prop1 = new JpaToscaProperty(new PfReferenceKey(dataType1.getKey(), "prop1")); + prop1.setType(dataType0v2.getKey()); + dataType1.getProperties().put(prop1.getKey().getLocalName(), prop1); + updatedServiceTemplate.getDataTypes().getConceptMap().put(dataType1.getKey(), dataType1); + new SimpleToscaProvider().createDataTypes(pfDao, updatedServiceTemplate); + + assertThatThrownBy(() -> new SimpleToscaProvider().deleteDataType(pfDao, dataType0v2.getKey())) + .hasMessage("data type DataType0:0.0.2 is in use, it is referenced in data type DataType1:0.0.3"); } @Test @@ -182,6 +236,42 @@ public class SimpleToscaProviderTest { assertEquals(policyType0, gotServiceTemplate.getPolicyTypes().get(policyType0Key)); assertEquals("Updated Description", gotServiceTemplate.getPolicyTypes().get(policyType0Key).getDescription()); + assertThatThrownBy(() -> { + new SimpleToscaProvider().deletePolicyType(pfDao, new PfConceptKey("IDontExist:0.0.1")); + }).hasMessage("policy type IDontExist:0.0.1 not found"); + + JpaToscaPolicyType pt1 = new JpaToscaPolicyType(new PfConceptKey("pt1:0.0.2")); + pt1.setDerivedFrom(policyType0Key); + serviceTemplate.getPolicyTypes().getConceptMap().put(pt1.getKey(), pt1); + new SimpleToscaProvider().createPolicyTypes(pfDao, serviceTemplate); + + assertThatThrownBy(() -> new SimpleToscaProvider().deletePolicyType(pfDao, policyType0Key)) + .hasMessage("policy type PolicyType0:0.0.1 is in use, it is referenced in policy type pt1:0.0.2"); + + serviceTemplate.setTopologyTemplate(new JpaToscaTopologyTemplate()); + serviceTemplate.getTopologyTemplate().setPolicies(new JpaToscaPolicies()); + + JpaToscaPolicy p0 = new JpaToscaPolicy(new PfConceptKey("p0:0.0.1")); + p0.setType(policyType0Key); + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(p0.getKey(), p0); + + JpaToscaPolicy p1 = new JpaToscaPolicy(new PfConceptKey("p1:0.0.1")); + p1.setType(pt1.getKey()); + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(p1.getKey(), p1); + new SimpleToscaProvider().createPolicies(pfDao, serviceTemplate); + + assertThatThrownBy(() -> new SimpleToscaProvider().deletePolicyType(pfDao, policyType0Key)) + .hasMessage("policy type PolicyType0:0.0.1 is in use, it is referenced in policy type pt1:0.0.2"); + + assertThatThrownBy(() -> new SimpleToscaProvider().deletePolicyType(pfDao, pt1.getKey())) + .hasMessage("policy type pt1:0.0.2 is in use, it is referenced in policy p1:0.0.1"); + + new SimpleToscaProvider().deletePolicy(pfDao, p1.getKey()); + + new SimpleToscaProvider().deletePolicyType(pfDao, pt1.getKey()); + + new SimpleToscaProvider().deletePolicy(pfDao, p0.getKey()); + JpaToscaServiceTemplate deletedServiceTemplate = new SimpleToscaProvider().deletePolicyType(pfDao, policyType0Key); @@ -190,7 +280,7 @@ public class SimpleToscaProviderTest { deletedServiceTemplate.getPolicyTypes().get(policyType0Key).getDescription()); assertThatThrownBy(() -> new SimpleToscaProvider().deletePolicyType(pfDao, policyType0Key)) - .hasMessage("policy types for PolicyType0:0.0.1 do not exist"); + .hasMessage("no policy types found"); } @Test @@ -232,7 +322,7 @@ public class SimpleToscaProviderTest { deletedServiceTemplate.getPolicyTypes().get(policyType0Key).getDescription()); assertThatThrownBy(() -> new SimpleToscaProvider().deletePolicyType(pfDao, policyType0Key)) - .hasMessage("policy types for PolicyType0:0.0.1 do not exist"); + .hasMessage("no policy types found"); } @Test @@ -259,6 +349,9 @@ public class SimpleToscaProviderTest { assertEquals(originalServiceTemplate.getTopologyTemplate().getPolicies().get(policyKey), gotServiceTemplate.getTopologyTemplate().getPolicies().get(policyKey)); + + JpaToscaServiceTemplate deletedServiceTemplate = new SimpleToscaProvider().deletePolicy(pfDao, policyKey); + assertEquals(1, deletedServiceTemplate.getTopologyTemplate().getPolicies().getConceptMap().size()); } @Test @@ -314,17 +407,20 @@ public class SimpleToscaProviderTest { PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0"); - JpaToscaServiceTemplate deletedServiceTemplate = - new SimpleToscaProvider().deletePolicy(pfDao, new PfConceptKey(policyKey)); + assertThatThrownBy(() -> new SimpleToscaProvider().deletePolicy(pfDao, new PfConceptKey("IDontExist:0.0.1"))) + .hasMessage("policy IDontExist:0.0.1 not found"); + + JpaToscaServiceTemplate deletedServiceTemplate = new SimpleToscaProvider().deletePolicy(pfDao, policyKey); assertEquals(originalServiceTemplate.getTopologyTemplate().getPolicies().get(policyKey), deletedServiceTemplate.getTopologyTemplate().getPolicies().get(policyKey)); - // @formatter:off - assertThatThrownBy( - () -> new SimpleToscaProvider().getPolicies(pfDao, policyKey.getName(), policyKey.getVersion())) - .hasMessage("policies for onap.restart.tca:1.0.0 do not exist"); - // @formatter:on + assertThatThrownBy(() -> { + new SimpleToscaProvider().getPolicies(pfDao, policyKey.getName(), policyKey.getVersion()); + }).hasMessage("policies for onap.restart.tca:1.0.0 do not exist"); + + assertThatThrownBy(() -> new SimpleToscaProvider().deletePolicy(pfDao, policyKey)) + .hasMessage("no policies found"); } @Test @@ -344,8 +440,219 @@ public class SimpleToscaProviderTest { } @Test + public void testGetServiceTemplate() throws PfModelException { + assertThatThrownBy(() -> new SimpleToscaProvider().getServiceTemplate(pfDao)) + .hasMessage("service template not found in database"); + } + + @Test + public void testAppendToServiceTemplate() throws PfModelException { + JpaToscaServiceTemplate serviceTemplateFragment = new JpaToscaServiceTemplate(); + serviceTemplateFragment.setPolicyTypes(new JpaToscaPolicyTypes()); + JpaToscaPolicyType badPt = new JpaToscaPolicyType(); + serviceTemplateFragment.getPolicyTypes().getConceptMap().put(badPt.getKey(), badPt); + + assertThatThrownBy(() -> new SimpleToscaProvider().appendToServiceTemplate(pfDao, serviceTemplateFragment)) + .hasMessageContaining( + "key on concept entry PfConceptKey(name=NULL, version=0.0.0) may not be the null key"); + } + + @Test + public void testGetDataTypesCornerCases() throws PfModelException { + assertThatThrownBy(() -> { + new SimpleToscaProvider().getDataTypes(pfDao, "hello", "0.0.1"); + }).hasMessageMatching("service template not found in database"); + + JpaToscaServiceTemplate serviceTemplate = new JpaToscaServiceTemplate(); + serviceTemplate.setPolicyTypes(new JpaToscaPolicyTypes()); + JpaToscaPolicyType p0 = new JpaToscaPolicyType(new PfConceptKey("p0:0.0.1")); + serviceTemplate.getPolicyTypes().getConceptMap().put(p0.getKey(), p0); + + new SimpleToscaProvider().createPolicyTypes(pfDao, serviceTemplate); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().getDataTypes(pfDao, "hello", "0.0.1"); + }).hasMessageMatching("data types for hello:0.0.1 do not exist"); + + serviceTemplate.setDataTypes(new JpaToscaDataTypes()); + + JpaToscaDataType p01 = new JpaToscaDataType(new PfConceptKey("dt0:0.0.1")); + serviceTemplate.getDataTypes().getConceptMap().put(p01.getKey(), p01); + + new SimpleToscaProvider().createDataTypes(pfDao, serviceTemplate); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().getDataTypes(pfDao, "hello", "0.0.1"); + }).hasMessageMatching("data types for hello:0.0.1 do not exist"); + + JpaToscaServiceTemplate gotSt = new SimpleToscaProvider().getDataTypes(pfDao, p01.getName(), p01.getVersion()); + + assertEquals(p01, gotSt.getDataTypes().get(p01.getKey())); + assertEquals(p01, gotSt.getDataTypes().get(p01.getName())); + assertEquals(p01, gotSt.getDataTypes().get(p01.getName(), null)); + assertEquals(p01, gotSt.getDataTypes().get(p01.getName(), p01.getVersion())); + assertEquals(1, gotSt.getDataTypes().getAll(null).size()); + assertEquals(1, gotSt.getDataTypes().getAll(null, null).size()); + assertEquals(1, gotSt.getDataTypes().getAll(p01.getName(), null).size()); + assertEquals(1, gotSt.getDataTypes().getAll(p01.getName(), p01.getVersion()).size()); + + JpaToscaDataType p02 = new JpaToscaDataType(new PfConceptKey("dt0:0.0.2")); + serviceTemplate.getDataTypes().getConceptMap().put(p02.getKey(), p02); + + new SimpleToscaProvider().createDataTypes(pfDao, serviceTemplate); + gotSt = new SimpleToscaProvider().getDataTypes(pfDao, p01.getName(), p01.getVersion()); + + assertEquals(p01, gotSt.getDataTypes().get(p01.getKey())); + assertEquals(p02, gotSt.getDataTypes().get(p01.getName())); + assertEquals(p02, gotSt.getDataTypes().get(p01.getName(), null)); + assertEquals(p01, gotSt.getDataTypes().get(p01.getName(), p01.getVersion())); + assertEquals(p02, gotSt.getDataTypes().get(p01.getName(), p02.getVersion())); + assertEquals(2, gotSt.getDataTypes().getAll(null).size()); + assertEquals(2, gotSt.getDataTypes().getAll(null, null).size()); + assertEquals(2, gotSt.getDataTypes().getAll(p01.getName(), null).size()); + assertEquals(1, gotSt.getDataTypes().getAll(p01.getName(), p02.getVersion()).size()); + } + + @Test + public void testGetPolicyTypesCornerCases() throws PfModelException { + assertThatThrownBy(() -> { + new SimpleToscaProvider().getPolicyTypes(pfDao, "hello", "0.0.1"); + }).hasMessageMatching("service template not found in database"); + + JpaToscaServiceTemplate serviceTemplate = new JpaToscaServiceTemplate(); + serviceTemplate.setDataTypes(new JpaToscaDataTypes()); + JpaToscaDataType dt0 = new JpaToscaDataType(new PfConceptKey("dt0:0.0.1")); + serviceTemplate.getDataTypes().getConceptMap().put(dt0.getKey(), dt0); + + new SimpleToscaProvider().createDataTypes(pfDao, serviceTemplate); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().getPolicyTypes(pfDao, "hello", "0.0.1"); + }).hasMessageMatching("policy types for hello:0.0.1 do not exist"); + + serviceTemplate.setPolicyTypes(new JpaToscaPolicyTypes()); + + JpaToscaPolicyType pt01 = new JpaToscaPolicyType(new PfConceptKey("p0:0.0.1")); + serviceTemplate.getPolicyTypes().getConceptMap().put(pt01.getKey(), pt01); + + new SimpleToscaProvider().createPolicyTypes(pfDao, serviceTemplate); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().getPolicyTypes(pfDao, "hello", "0.0.1"); + }).hasMessageMatching("policy types for hello:0.0.1 do not exist"); + + JpaToscaServiceTemplate gotSt = + new SimpleToscaProvider().getPolicyTypes(pfDao, pt01.getName(), pt01.getVersion()); + + assertEquals(pt01, gotSt.getPolicyTypes().get(pt01.getKey())); + assertEquals(pt01, gotSt.getPolicyTypes().get(pt01.getName())); + assertEquals(pt01, gotSt.getPolicyTypes().get(pt01.getName(), null)); + assertEquals(pt01, gotSt.getPolicyTypes().get(pt01.getName(), pt01.getVersion())); + assertEquals(1, gotSt.getPolicyTypes().getAll(null).size()); + assertEquals(1, gotSt.getPolicyTypes().getAll(null, null).size()); + assertEquals(1, gotSt.getPolicyTypes().getAll(pt01.getName(), null).size()); + assertEquals(1, gotSt.getPolicyTypes().getAll(pt01.getName(), pt01.getVersion()).size()); + + JpaToscaPolicyType pt02 = new JpaToscaPolicyType(new PfConceptKey("p0:0.0.2")); + serviceTemplate.getPolicyTypes().getConceptMap().put(pt02.getKey(), pt02); + + new SimpleToscaProvider().createPolicyTypes(pfDao, serviceTemplate); + gotSt = new SimpleToscaProvider().getPolicyTypes(pfDao, pt01.getName(), pt01.getVersion()); + + assertEquals(pt01, gotSt.getPolicyTypes().get(pt01.getKey())); + assertEquals(pt02, gotSt.getPolicyTypes().get(pt01.getName())); + assertEquals(pt02, gotSt.getPolicyTypes().get(pt01.getName(), null)); + assertEquals(pt01, gotSt.getPolicyTypes().get(pt01.getName(), pt01.getVersion())); + assertEquals(pt02, gotSt.getPolicyTypes().get(pt01.getName(), pt02.getVersion())); + assertEquals(2, gotSt.getPolicyTypes().getAll(null).size()); + assertEquals(2, gotSt.getPolicyTypes().getAll(null, null).size()); + assertEquals(2, gotSt.getPolicyTypes().getAll(pt01.getName(), null).size()); + assertEquals(1, gotSt.getPolicyTypes().getAll(pt01.getName(), pt02.getVersion()).size()); + } + + @Test + public void testGetPoliciesCornerCases() throws PfModelException { + assertThatThrownBy(() -> { + new SimpleToscaProvider().getPolicies(pfDao, "hello", "0.0.1"); + }).hasMessageMatching("service template not found in database"); + + JpaToscaServiceTemplate serviceTemplate = new JpaToscaServiceTemplate(); + serviceTemplate.setDataTypes(new JpaToscaDataTypes()); + JpaToscaDataType dt0 = new JpaToscaDataType(new PfConceptKey("dt0:0.0.1")); + serviceTemplate.getDataTypes().getConceptMap().put(dt0.getKey(), dt0); + + new SimpleToscaProvider().createDataTypes(pfDao, serviceTemplate); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().getPolicies(pfDao, "hello", "0.0.1"); + }).hasMessageMatching("policies for hello:0.0.1 do not exist"); + + serviceTemplate.setPolicyTypes(new JpaToscaPolicyTypes()); + + JpaToscaPolicyType pt01 = new JpaToscaPolicyType(new PfConceptKey("pt0:0.0.1")); + serviceTemplate.getPolicyTypes().getConceptMap().put(pt01.getKey(), pt01); + + serviceTemplate.setTopologyTemplate(new JpaToscaTopologyTemplate()); + serviceTemplate.getTopologyTemplate().setPolicies(new JpaToscaPolicies()); + + JpaToscaPolicy p01 = new JpaToscaPolicy(new PfConceptKey("p0:0.0.1")); + p01.setType(pt01.getKey()); + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(p01.getKey(), p01); + + new SimpleToscaProvider().createPolicies(pfDao, serviceTemplate); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().getPolicies(pfDao, "hello", "0.0.1"); + }).hasMessageMatching("policies for hello:0.0.1 do not exist"); + + JpaToscaServiceTemplate gotSt = new SimpleToscaProvider().getPolicies(pfDao, p01.getName(), p01.getVersion()); + + assertEquals(p01, gotSt.getTopologyTemplate().getPolicies().get(p01.getKey())); + assertEquals(p01, gotSt.getTopologyTemplate().getPolicies().get(p01.getName())); + assertEquals(p01, gotSt.getTopologyTemplate().getPolicies().get(p01.getName(), null)); + assertEquals(p01, gotSt.getTopologyTemplate().getPolicies().get(p01.getName(), p01.getVersion())); + assertEquals(1, gotSt.getTopologyTemplate().getPolicies().getAll(null).size()); + assertEquals(1, gotSt.getTopologyTemplate().getPolicies().getAll(null, null).size()); + assertEquals(1, gotSt.getTopologyTemplate().getPolicies().getAll(p01.getName(), null).size()); + assertEquals(1, gotSt.getTopologyTemplate().getPolicies().getAll(p01.getName(), p01.getVersion()).size()); + + JpaToscaPolicy p02 = new JpaToscaPolicy(new PfConceptKey("p0:0.0.2")); + p02.setType(pt01.getKey()); + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(p02.getKey(), p02); + + new SimpleToscaProvider().createPolicies(pfDao, serviceTemplate); + gotSt = new SimpleToscaProvider().getPolicies(pfDao, p01.getName(), p01.getVersion()); + + assertEquals(p01, gotSt.getTopologyTemplate().getPolicies().get(p01.getKey())); + assertEquals(p02, gotSt.getTopologyTemplate().getPolicies().get(p01.getName())); + assertEquals(p02, gotSt.getTopologyTemplate().getPolicies().get(p01.getName(), null)); + assertEquals(p01, gotSt.getTopologyTemplate().getPolicies().get(p01.getName(), p01.getVersion())); + assertEquals(p02, gotSt.getTopologyTemplate().getPolicies().get(p01.getName(), p02.getVersion())); + assertEquals(2, gotSt.getTopologyTemplate().getPolicies().getAll(null).size()); + assertEquals(2, gotSt.getTopologyTemplate().getPolicies().getAll(null, null).size()); + assertEquals(2, gotSt.getTopologyTemplate().getPolicies().getAll(p01.getName(), null).size()); + assertEquals(1, gotSt.getTopologyTemplate().getPolicies().getAll(p01.getName(), p02.getVersion()).size()); + } + + @Test public void testNonNulls() { assertThatThrownBy(() -> { + new SimpleToscaProvider().getServiceTemplate(null); + }).hasMessageMatching(DAO_IS_NULL); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().appendToServiceTemplate(null, null); + }).hasMessageMatching(DAO_IS_NULL); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().appendToServiceTemplate(null, new JpaToscaServiceTemplate()); + }).hasMessageMatching(DAO_IS_NULL); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().appendToServiceTemplate(pfDao, null); + }).hasMessageMatching("^incomingServiceTemplateFragment is marked .*on.*ull but is null$"); + + assertThatThrownBy(() -> { new SimpleToscaProvider().getDataTypes(null, null, null); }).hasMessageMatching(DAO_IS_NULL); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java index 0a8283e98..270bc6c77 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java @@ -199,8 +199,9 @@ public class MonitoringPolicyTypeSerializationTest { assertTrue(firstDataTypeFirstProperty.getConstraints().size() == 1); assertEquals("org.onap.policy.models.tosca.simple.concepts.JpaToscaConstraintValidValues", firstDataTypeFirstProperty.getConstraints().iterator().next().getClass().getName()); - assertTrue(((JpaToscaConstraintValidValues) (firstDataTypeFirstProperty.getConstraints().iterator().next())) - .getValidValues().size() == 2); + assertEquals(2, + ((JpaToscaConstraintValidValues) (firstDataTypeFirstProperty.getConstraints().iterator().next())) + .getValidValues().size()); JpaToscaProperty firstDataTypeSecondProperty = firstDataTypePropertiesIter.next(); assertEquals(METRICS, firstDataTypeSecondProperty.getKey().getParentKeyName()); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/OptimizationPolicyTypeSerializationTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/OptimizationPolicyTypeSerializationTest.java index e710faa31..fb258a215 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/OptimizationPolicyTypeSerializationTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/OptimizationPolicyTypeSerializationTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,11 +21,11 @@ package org.onap.policy.models.tosca.simple.serialization; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.Map; + import org.junit.Before; import org.junit.Test; import org.onap.policy.common.utils.coder.CoderException; @@ -115,8 +116,8 @@ public class OptimizationPolicyTypeSerializationTest { return coder.encode(auth); } - private void validate(String testnm, JpaToscaServiceTemplate svctmpl, String derivedFrom, - String typeName, boolean checkResource, boolean checkService) { + private void validate(String testnm, JpaToscaServiceTemplate svctmpl, String derivedFrom, String typeName, + boolean checkResource, boolean checkService) { JpaToscaPolicyTypes policyTypes = svctmpl.getPolicyTypes(); assertEquals(testnm + " type count", 1, policyTypes.getConceptMap().size()); @@ -194,7 +195,7 @@ public class OptimizationPolicyTypeSerializationTest { String testnm = testName + " identity"; assertNotNull(testnm, prop); - assertNull(testnm + " metadata", prop.getMetadata()); + assertEquals(testnm + " metadata", 0, prop.getMetadata().size()); } private void validateMatchable(String testName, Map<String, String> metadata) { diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/utils/ToscaUtilsTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/utils/ToscaUtilsTest.java index a5d145e39..d75e37be2 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/utils/ToscaUtilsTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/utils/ToscaUtilsTest.java @@ -231,6 +231,14 @@ public class ToscaUtilsTest { assertEquals(2, ToscaUtils.getEntityTypeAncestors(dataTypes, dt2, result).size()); assertTrue(result.isValid()); + dt0.setDerivedFrom(dt0.getKey()); + assertThatThrownBy(() -> { + ToscaUtils.getEntityTypeAncestors(dataTypes, dt0, new PfValidationResult()); + }).hasMessageContaining("entity cannot be an ancestor of itself"); + + dt0.setDerivedFrom(null); + assertEquals(2, ToscaUtils.getEntityTypeAncestors(dataTypes, dt2, result).size()); + dt1.setDerivedFrom(new PfConceptKey("tosca.datatyps.Root", PfKey.NULL_KEY_VERSION)); assertTrue(ToscaUtils.getEntityTypeAncestors(dataTypes, dt0, result).isEmpty()); assertTrue(ToscaUtils.getEntityTypeAncestors(dataTypes, dt1, result).isEmpty()); |