From e9af3a2b3a430626c740b18ccf8592706db1dfb1 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Thu, 11 Jun 2020 19:00:41 -0400 Subject: Moving common polling code into HttpOperation SO and VFC have duplicate code for polling. Moved it into the common superclass. Issue-ID: POLICY-2632 Change-Id: I27128bfb2d54ef522b6b44ff569819a8463f3454 Signed-off-by: Jim Hahn --- .../impl/BidirectionalTopicOperator.java | 52 +---- .../actorserviceprovider/impl/HttpActor.java | 2 +- .../actorserviceprovider/impl/HttpOperation.java | 134 ++++++++++- .../actorserviceprovider/impl/HttpOperator.java | 43 +--- .../impl/HttpPollingOperator.java | 81 +++++++ .../actorserviceprovider/impl/TypedOperator.java | 97 ++++++++ .../parameters/HttpPollingActorParams.java | 59 +++++ .../parameters/HttpPollingConfig.java | 66 ++++++ .../parameters/HttpPollingParams.java | 58 +++++ .../impl/BidirectionalTopicOperatorTest.java | 6 +- .../impl/HttpPollingOperationTest.java | 255 +++++++++++++++++++++ .../impl/HttpPollingOperatorTest.java | 117 ++++++++++ .../parameters/HttpPollingActorParamsTest.java | 118 ++++++++++ .../parameters/HttpPollingConfigTest.java | 82 +++++++ .../parameters/HttpPollingParamsTest.java | 91 ++++++++ 15 files changed, 1168 insertions(+), 93 deletions(-) create mode 100644 models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperator.java create mode 100644 models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/TypedOperator.java create mode 100644 models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingActorParams.java create mode 100644 models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingConfig.java create mode 100644 models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingParams.java create mode 100644 models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperationTest.java create mode 100644 models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperatorTest.java create mode 100644 models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingActorParamsTest.java create mode 100644 models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingConfigTest.java create mode 100644 models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingParamsTest.java (limited to 'models-interactions/model-actors/actorServiceProvider/src') diff --git a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/BidirectionalTopicOperator.java b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/BidirectionalTopicOperator.java index 43c8b8872..0745c3aba 100644 --- a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/BidirectionalTopicOperator.java +++ b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/BidirectionalTopicOperator.java @@ -23,14 +23,10 @@ package org.onap.policy.controlloop.actorserviceprovider.impl; import java.util.Arrays; import java.util.List; import java.util.Map; -import lombok.Getter; import org.onap.policy.common.parameters.ValidationResult; -import org.onap.policy.controlloop.actorserviceprovider.Operation; import org.onap.policy.controlloop.actorserviceprovider.Util; import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig; import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicParams; -import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; -import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams; import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException; import org.onap.policy.controlloop.actorserviceprovider.topic.BidirectionalTopicHandler; import org.onap.policy.controlloop.actorserviceprovider.topic.BidirectionalTopicManager; @@ -40,13 +36,8 @@ import org.onap.policy.controlloop.actorserviceprovider.topic.SelectorKey; * Operator that uses a bidirectional topic. Topic operators may share a * {@link BidirectionalTopicHandler}. */ -public class BidirectionalTopicOperator extends OperatorPartial { - - /** - * Function to make an operation. - */ - @SuppressWarnings("rawtypes") - private final OperationMaker operationMaker; +public class BidirectionalTopicOperator + extends TypedOperator> { /** * Manager from which to get the topic handlers. @@ -58,12 +49,6 @@ public class BidirectionalTopicOperator extends OperatorPartial { */ private final List selectorKeys; - /** - * Current configuration. This is set by {@link #doConfigure(Map)}. - */ - @Getter - private BidirectionalTopicConfig currentConfig; - /** * Constructs the object. @@ -88,17 +73,13 @@ public class BidirectionalTopicOperator extends OperatorPartial { * @param selectorKeys keys used to extract the fields used to select responses for * this operator */ - // @formatter:off public BidirectionalTopicOperator(String actorName, String name, BidirectionalTopicManager topicManager, List selectorKeys, - @SuppressWarnings("rawtypes") OperationMaker - operationMaker) { - // @formatter:on + OperationMaker> operationMaker) { - super(actorName, name); + super(actorName, name, operationMaker); this.topicManager = topicManager; this.selectorKeys = selectorKeys; - this.operationMaker = operationMaker; } /** @@ -110,24 +91,12 @@ public class BidirectionalTopicOperator extends OperatorPartial { * @param selectorKeys keys used to extract the fields used to select responses for * this operator */ - // @formatter:off public BidirectionalTopicOperator(String actorName, String name, BidirectionalTopicManager topicManager, - @SuppressWarnings("rawtypes") OperationMaker - operationMaker, + OperationMaker> operationMaker, SelectorKey... selectorKeys) { - // @formatter:on this(actorName, name, topicManager, Arrays.asList(selectorKeys), operationMaker); } - /** - * Translates the parameters to an {@link HttpParams} and then extracts the relevant - * values. - */ - @Override - protected void doConfigure(Map parameters) { - currentConfig = makeConfiguration(parameters); - } - /** * Makes a new configuration using the specified parameters. * @@ -143,15 +112,4 @@ public class BidirectionalTopicOperator extends OperatorPartial { return new BidirectionalTopicConfig(getBlockingExecutor(), params, topicManager, selectorKeys); } - - @Override - public Operation buildOperation(ControlLoopOperationParams params) { - if (operationMaker == null) { - throw new UnsupportedOperationException("cannot make operation for " + getFullName()); - } - - verifyRunning(); - - return operationMaker.apply(params, currentConfig); - } } diff --git a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpActor.java b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpActor.java index eb5662f23..5a6081611 100644 --- a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpActor.java +++ b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpActor.java @@ -34,7 +34,7 @@ import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpActorPara public class HttpActor

extends ActorImpl { /** - * Class of parameters. + * Class of Actor parameters. */ private final Class

paramsClass; diff --git a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpOperation.java b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpOperation.java index fb6d38292..4800b3a4b 100644 --- a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpOperation.java +++ b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpOperation.java @@ -25,6 +25,7 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.function.Function; import javax.ws.rs.client.InvocationCallback; import javax.ws.rs.core.Response; @@ -38,6 +39,7 @@ import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig; import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture; import org.onap.policy.controlloop.policy.PolicyResult; import org.slf4j.Logger; @@ -52,6 +54,13 @@ import org.slf4j.LoggerFactory; public abstract class HttpOperation extends OperationPartial { private static final Logger logger = LoggerFactory.getLogger(HttpOperation.class); + /** + * Response status. + */ + public enum Status { + SUCCESS, FAILURE, STILL_WAITING + } + /** * Configuration for this operation. */ @@ -62,6 +71,18 @@ public abstract class HttpOperation extends OperationPartial { */ private final Class responseClass; + /** + * {@code True} to use polling, {@code false} otherwise. + */ + @Getter + private boolean usePolling; + + /** + * Number of polls issued so far, on the current operation attempt. + */ + @Getter + private int pollCount; + /** * Constructs the object. @@ -76,6 +97,17 @@ public abstract class HttpOperation extends OperationPartial { this.responseClass = clazz; } + /** + * Indicates that polling should be used. + */ + protected void setUsePolling() { + if (!(config instanceof HttpPollingConfig)) { + throw new IllegalStateException("cannot poll without polling parameters"); + } + + usePolling = true; + } + public HttpClient getClient() { return config.getClient(); } @@ -122,6 +154,17 @@ public abstract class HttpOperation extends OperationPartial { return (getClient().getBaseUrl() + getPath()); } + /** + * Resets the polling count + * + *

+ * Note: This should be invoked at the start of each operation (i.e., in + * {@link #startOperationAsync(int, OperationOutcome)}. + */ + protected void resetPollCount() { + pollCount = 0; + } + /** * Arranges to handle a response. * @@ -234,7 +277,88 @@ public abstract class HttpOperation extends OperationPartial { protected CompletableFuture postProcessResponse(OperationOutcome outcome, String url, Response rawResponse, T response) { - return CompletableFuture.completedFuture(outcome); + if (!usePolling) { + // doesn't use polling - just return the completed future + return CompletableFuture.completedFuture(outcome); + } + + HttpPollingConfig cfg = (HttpPollingConfig) config; + + switch (detmStatus(rawResponse, response)) { + case SUCCESS: + logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(), + params.getRequestId()); + return CompletableFuture + .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response)); + + case FAILURE: + logger.info("{}.{} request failed for {}", params.getActor(), params.getOperation(), + params.getRequestId()); + return CompletableFuture + .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response)); + + case STILL_WAITING: + default: + logger.info("{}.{} request incomplete for {}", params.getActor(), params.getOperation(), + params.getRequestId()); + break; + } + + // still incomplete + + // see if the limit for the number of polls has been reached + if (pollCount++ >= cfg.getMaxPolls()) { + logger.warn("{}: execeeded 'poll' limit {} for {}", getFullName(), cfg.getMaxPolls(), + params.getRequestId()); + setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT); + return CompletableFuture.completedFuture(outcome); + } + + // sleep and then poll + Function> doPoll = unused -> issuePoll(outcome); + return sleep(getPollWaitMs(), TimeUnit.MILLISECONDS).thenComposeAsync(doPoll); + } + + /** + * Polls to see if the original request is complete. This method polls using an HTTP + * "get" request whose URL is constructed by appending the extracted "poll ID" to the + * poll path from the configuration data. + * + * @param outcome outcome to be populated with the response + * @return a future that can be used to cancel the poll or await its response + */ + protected CompletableFuture issuePoll(OperationOutcome outcome) { + String path = getPollingPath(); + String url = getClient().getBaseUrl() + path; + + logger.debug("{}: 'poll' count {} for {}", getFullName(), pollCount, params.getRequestId()); + + logMessage(EventType.OUT, CommInfrastructure.REST, url, null); + + return handleResponse(outcome, url, callback -> getClient().get(callback, path, null)); + } + + /** + * Determines the status of the response. This particular method simply throws an + * exception. + * + * @param rawResponse raw response + * @param response decoded response + * @return the status of the response + */ + protected Status detmStatus(Response rawResponse, T response) { + throw new UnsupportedOperationException("cannot determine response status"); + } + + /** + * Gets the URL to use when polling. Typically, this is some unique ID appended to the + * polling path found within the configuration data. This particular method simply + * returns the polling path from the configuration data. + * + * @return the URL to use when polling + */ + protected String getPollingPath() { + return ((HttpPollingConfig) config).getPollPath(); } /** @@ -255,4 +379,12 @@ public abstract class HttpOperation extends OperationPartial { NetLoggerUtil.log(direction, infra, sink, json); return json; } + + // these may be overridden by junit tests + + protected long getPollWaitMs() { + HttpPollingConfig cfg = (HttpPollingConfig) config; + + return TimeUnit.MILLISECONDS.convert(cfg.getPollWaitSec(), TimeUnit.SECONDS); + } } diff --git a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpOperator.java b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpOperator.java index 9e446a7c8..f731a2c84 100644 --- a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpOperator.java +++ b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpOperator.java @@ -21,13 +21,10 @@ package org.onap.policy.controlloop.actorserviceprovider.impl; import java.util.Map; -import lombok.Getter; import org.onap.policy.common.endpoints.http.client.HttpClientFactory; import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; import org.onap.policy.common.parameters.ValidationResult; -import org.onap.policy.controlloop.actorserviceprovider.Operation; import org.onap.policy.controlloop.actorserviceprovider.Util; -import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams; import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException; @@ -35,20 +32,7 @@ import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterVali /** * Operator that uses HTTP. The operator's parameters must be an {@link HttpParams}. */ -public class HttpOperator extends OperatorPartial { - - /** - * Function to make an operation. - */ - @SuppressWarnings("rawtypes") - private final OperationMaker operationMaker; - - /** - * Current configuration. This is set by {@link #doConfigure(Map)}. - */ - @Getter - private HttpConfig currentConfig; - +public class HttpOperator extends TypedOperator> { /** * Constructs the object. @@ -68,18 +52,8 @@ public class HttpOperator extends OperatorPartial { * @param operationMaker function to make an operation */ public HttpOperator(String actorName, String name, - @SuppressWarnings("rawtypes") OperationMaker operationMaker) { - super(actorName, name); - this.operationMaker = operationMaker; - } - - /** - * Translates the parameters to an {@link HttpParams} and then extracts the relevant - * values. - */ - @Override - protected void doConfigure(Map parameters) { - currentConfig = makeConfiguration(parameters); + OperationMaker> operationMaker) { + super(actorName, name, operationMaker); } /** @@ -98,17 +72,6 @@ public class HttpOperator extends OperatorPartial { return new HttpConfig(getBlockingExecutor(), params, getClientFactory()); } - @Override - public Operation buildOperation(ControlLoopOperationParams params) { - if (operationMaker == null) { - throw new UnsupportedOperationException("cannot make operation for " + getFullName()); - } - - verifyRunning(); - - return operationMaker.apply(params, currentConfig); - } - // these may be overridden by junit tests protected HttpClientFactory getClientFactory() { diff --git a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperator.java b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperator.java new file mode 100644 index 000000000..9e681ceeb --- /dev/null +++ b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperator.java @@ -0,0 +1,81 @@ +/*- + * ============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.actorserviceprovider.impl; + +import java.util.Map; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; +import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingParams; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException; + +/** + * Operator that uses HTTP and polls for the request completion status. The operator's + * parameters must be an {@link HttpPollingParams}. + */ +public class HttpPollingOperator extends TypedOperator> { + + /** + * Constructs the object. + * + * @param actorName name of the actor with which this operator is associated + * @param name operation name + */ + protected HttpPollingOperator(String actorName, String name) { + this(actorName, name, null); + } + + /** + * Constructs the object. + * + * @param actorName name of the actor with which this operator is associated + * @param name operation name + * @param operationMaker function to make an operation + */ + public HttpPollingOperator(String actorName, String name, + OperationMaker> operationMaker) { + super(actorName, name, operationMaker); + } + + /** + * Makes a new configuration using the specified parameters. + * + * @param parameters operator parameters + * @return a new configuration + */ + protected HttpPollingConfig makeConfiguration(Map parameters) { + HttpPollingParams params = Util.translate(getFullName(), parameters, HttpPollingParams.class); + ValidationResult result = params.validate(getFullName()); + if (!result.isValid()) { + throw new ParameterValidationRuntimeException("invalid parameters", result); + } + + return new HttpPollingConfig(getBlockingExecutor(), params, getClientFactory()); + } + + // these may be overridden by junit tests + + protected HttpClientFactory getClientFactory() { + return HttpClientFactoryInstance.getClientFactory(); + } +} diff --git a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/TypedOperator.java b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/TypedOperator.java new file mode 100644 index 000000000..5561a97ef --- /dev/null +++ b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/impl/TypedOperator.java @@ -0,0 +1,97 @@ +/*- + * ============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.actorserviceprovider.impl; + +import java.util.Map; +import lombok.Getter; +import org.onap.policy.controlloop.actorserviceprovider.Operation; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams; + +/** + * Operator with typed parameter information. + * + * @param type of configuration data + * @param type of operation that the operator creates + */ +public abstract class TypedOperator extends OperatorPartial { + + /** + * Function to make an operation. + */ + private final OperationMaker operationMaker; + + /** + * Current configuration. This is set by {@link #doConfigure(Map)}. + */ + @Getter + private C currentConfig; + + + /** + * Constructs the object. + * + * @param actorName name of the actor with which this operator is associated + * @param name operation name + */ + protected TypedOperator(String actorName, String name) { + this(actorName, name, null); + } + + /** + * Constructs the object. + * + * @param actorName name of the actor with which this operator is associated + * @param name operation name + * @param operationMaker function to make an operation + */ + public TypedOperator(String actorName, String name, OperationMaker operationMaker) { + super(actorName, name); + this.operationMaker = operationMaker; + } + + /** + * Translates the parameters, saving the relevant configuration data. + */ + @Override + protected void doConfigure(Map parameters) { + currentConfig = makeConfiguration(parameters); + } + + /** + * Makes a new configuration using the specified parameters. + * + * @param parameters operator parameters + * @return a new configuration + */ + protected abstract C makeConfiguration(Map parameters); + + @Override + public T buildOperation(ControlLoopOperationParams params) { + if (operationMaker == null) { + throw new UnsupportedOperationException("cannot make operation for " + getFullName()); + } + + verifyRunning(); + + return operationMaker.apply(params, currentConfig); + } +} diff --git a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingActorParams.java b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingActorParams.java new file mode 100644 index 000000000..3343c5b3c --- /dev/null +++ b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingActorParams.java @@ -0,0 +1,59 @@ +/*- + * ============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.actorserviceprovider.parameters; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpActorParams; + +/** + * Parameters used by Actors that, after issuing an HTTP request, must poll the target + * server to determine the request completion status. + */ +@Getter +@Setter +@EqualsAndHashCode(callSuper = true) +public class HttpPollingActorParams extends HttpActorParams { + + /* + * Optional, default values that are used if missing from the operation-specific + * parameters. + */ + + /** + * Path to use when polling for request completion. + */ + private String pollPath; + + /** + * Maximum number of times to poll to retrieve the response. + */ + @Min(0) + private int maxPolls = 3; + + /** + * Time, in seconds, to wait between polling. + */ + @Min(1) + private int pollWaitSec = 20; +} diff --git a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingConfig.java b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingConfig.java new file mode 100644 index 000000000..8e0daa07c --- /dev/null +++ b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingConfig.java @@ -0,0 +1,66 @@ +/*- + * ============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.actorserviceprovider.parameters; + +import java.util.concurrent.Executor; +import lombok.Getter; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; + +/** + * Configuration for HTTP Operators that, after issuing a request, must poll the target + * server to determine the request completion status. + */ +@Getter +public class HttpPollingConfig extends HttpConfig { + + /** + * Path to use when polling for request completion. A trailing "/" is added, if it is + * missing. + */ + private String pollPath; + + /** + * Maximum number of times to poll to retrieve the response. + */ + private int maxPolls; + + /** + * Time, in seconds, to wait between polling. + */ + private int pollWaitSec; + + + /** + * Constructs the object. + * + * @param blockingExecutor executor to be used for tasks that may perform blocking I/O + * @param params operator parameters + * @param clientFactory factory from which to obtain the {@link HttpClient} + */ + public HttpPollingConfig(Executor blockingExecutor, HttpPollingParams params, HttpClientFactory clientFactory) { + super(blockingExecutor, params, clientFactory); + + this.pollPath = params.getPollPath() + (params.getPollPath().endsWith("/") ? "" : "/"); + this.maxPolls = params.getMaxPolls(); + this.pollWaitSec = params.getPollWaitSec(); + } +} diff --git a/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingParams.java b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingParams.java new file mode 100644 index 000000000..2f33bd217 --- /dev/null +++ b/models-interactions/model-actors/actorServiceProvider/src/main/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingParams.java @@ -0,0 +1,58 @@ +/*- + * ============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.actorserviceprovider.parameters; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.SuperBuilder; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams; + +/** + * Parameters used by Operators that, after issuing an HTTP request, must poll the target + * server to determine the request completion status. + */ +@NotNull +@NotBlank +@Data +@EqualsAndHashCode(callSuper = true) +@SuperBuilder(toBuilder = true) +public class HttpPollingParams extends HttpParams { + + /** + * Path to use when polling for request completion. + */ + private String pollPath; + + /** + * Maximum number of times to poll to retrieve the response. + */ + @Min(0) + private int maxPolls; + + /** + * Time, in seconds, to wait between polling. + */ + @Min(1) + private int pollWaitSec; +} diff --git a/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/BidirectionalTopicOperatorTest.java b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/BidirectionalTopicOperatorTest.java index b5e3de32c..29f507e60 100644 --- a/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/BidirectionalTopicOperatorTest.java +++ b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/BidirectionalTopicOperatorTest.java @@ -34,7 +34,6 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.onap.policy.controlloop.actorserviceprovider.Operation; import org.onap.policy.controlloop.actorserviceprovider.Util; import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig; import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicParams; @@ -108,8 +107,7 @@ public class BidirectionalTopicOperatorTest { AtomicReference configRef = new AtomicReference<>(); // @formatter:off - @SuppressWarnings("rawtypes") - OperationMaker maker = + OperationMaker> maker = (params, config) -> { paramsRef.set(params); configRef.set(config); @@ -152,7 +150,7 @@ public class BidirectionalTopicOperatorTest { } @Override - public Operation buildOperation(ControlLoopOperationParams params) { + public BidirectionalTopicOperation buildOperation(ControlLoopOperationParams params) { return null; } } diff --git a/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperationTest.java b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperationTest.java new file mode 100644 index 000000000..ed5ba9b56 --- /dev/null +++ b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperationTest.java @@ -0,0 +1,255 @@ +/*- + * ============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.actorserviceprovider.impl; + +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; +import javax.ws.rs.client.InvocationCallback; +import javax.ws.rs.core.Response; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.stubbing.Answer; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig; +import org.onap.policy.controlloop.policy.PolicyResult; + +/** + * Tests HttpOperation when polling is enabled. + */ +public class HttpPollingOperationTest { + private static final String BASE_URI = "http://my-host:6969/base-uri/"; + private static final String MY_PATH = "my-path"; + private static final String FULL_PATH = BASE_URI + MY_PATH; + private static final int MAX_POLLS = 3; + private static final int POLL_WAIT_SEC = 20; + private static final String POLL_PATH = "my-poll-path"; + private static final String MY_ACTOR = "my-actor"; + private static final String MY_OPERATION = "my-operation"; + private static final String MY_RESPONSE = "my-response"; + private static final int RESPONSE_ACCEPT = 100; + private static final int RESPONSE_SUCCESS = 200; + private static final int RESPONSE_FAILURE = 500; + + @Mock + private HttpPollingConfig config; + @Mock + private HttpClient client; + @Mock + private Response rawResponse; + + protected ControlLoopOperationParams params; + private String response; + private OperationOutcome outcome; + + private HttpOperation oper; + + /** + * Sets up. + */ + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + + when(client.getBaseUrl()).thenReturn(BASE_URI); + + when(config.getClient()).thenReturn(client); + when(config.getPath()).thenReturn(MY_PATH); + when(config.getMaxPolls()).thenReturn(MAX_POLLS); + when(config.getPollPath()).thenReturn(POLL_PATH); + when(config.getPollWaitSec()).thenReturn(POLL_WAIT_SEC); + + response = MY_RESPONSE; + + when(rawResponse.getStatus()).thenReturn(RESPONSE_SUCCESS); + when(rawResponse.readEntity(String.class)).thenReturn(response); + + params = ControlLoopOperationParams.builder().actor(MY_ACTOR).operation(MY_OPERATION).build(); + outcome = params.makeOutcome(); + + oper = new MyOper(params, config); + } + + @Test + public void testConstructor_testGetWaitMsGet() { + assertEquals(MY_ACTOR, oper.getActorName()); + assertEquals(MY_OPERATION, oper.getName()); + assertSame(config, oper.getConfig()); + assertEquals(1000 * POLL_WAIT_SEC, oper.getPollWaitMs()); + } + + @Test + public void testSetUsePollExceptions() { + // should be no exception + oper.setUsePolling(); + + // should throw an exception if we pass a plain HttpConfig + HttpConfig config2 = mock(HttpConfig.class); + when(config2.getClient()).thenReturn(client); + when(config2.getPath()).thenReturn(MY_PATH); + + assertThatIllegalStateException().isThrownBy(() -> new MyOper(params, config2).setUsePolling()); + } + + @Test + public void testPostProcess() throws Exception { + // completed + oper.generateSubRequestId(2); + CompletableFuture future2 = + oper.postProcessResponse(outcome, FULL_PATH, rawResponse, response); + assertTrue(future2.isDone()); + assertSame(outcome, future2.get()); + assertEquals(PolicyResult.SUCCESS, outcome.getResult()); + assertNotNull(oper.getSubRequestId()); + assertSame(response, outcome.getResponse()); + + // failed + oper.generateSubRequestId(2); + when(rawResponse.getStatus()).thenReturn(RESPONSE_FAILURE); + future2 = oper.postProcessResponse(outcome, FULL_PATH, rawResponse, response); + assertTrue(future2.isDone()); + assertSame(outcome, future2.get()); + assertEquals(PolicyResult.FAILURE, outcome.getResult()); + assertNotNull(oper.getSubRequestId()); + assertSame(response, outcome.getResponse()); + } + + /** + * Tests postProcess() when the poll is repeated a couple of times. + */ + @Test + public void testPostProcessRepeated_testResetGetCount() throws Exception { + /* + * Two accepts and then a success - should result in two polls. + */ + when(rawResponse.getStatus()).thenReturn(RESPONSE_ACCEPT, RESPONSE_ACCEPT, RESPONSE_SUCCESS, RESPONSE_SUCCESS); + + when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse)); + + // use a real executor + params = params.toBuilder().executor(ForkJoinPool.commonPool()).build(); + + oper = new MyOper(params, config) { + @Override + public long getPollWaitMs() { + return 1; + } + }; + + CompletableFuture future2 = + oper.postProcessResponse(outcome, FULL_PATH, rawResponse, response); + + assertSame(outcome, future2.get(5, TimeUnit.SECONDS)); + assertEquals(PolicyResult.SUCCESS, outcome.getResult()); + assertEquals(2, oper.getPollCount()); + + /* + * repeat - this time, the "poll" count will be exhausted, so it should fail + */ + when(rawResponse.getStatus()).thenReturn(RESPONSE_ACCEPT); + + future2 = oper.postProcessResponse(outcome, FULL_PATH, rawResponse, response); + + assertSame(outcome, future2.get(5, TimeUnit.SECONDS)); + assertEquals(PolicyResult.FAILURE_TIMEOUT, outcome.getResult()); + assertEquals(MAX_POLLS + 1, oper.getPollCount()); + + oper.resetPollCount(); + assertEquals(0, oper.getPollCount()); + assertNull(oper.getSubRequestId()); + } + + @Test + public void testDetmStatus() { + // make an operation that does NOT override detmStatus() + oper = new HttpOperation(params, config, String.class) {}; + + assertThatThrownBy(() -> oper.detmStatus(rawResponse, response)) + .isInstanceOf(UnsupportedOperationException.class); + } + + /** + * Provides a response to an asynchronous HttpClient call. + * + * @param response response to be provided to the call + * @return a function that provides the response to the call + */ + protected Answer> provideResponse(Response response) { + return provideResponse(response, 0); + } + + /** + * Provides a response to an asynchronous HttpClient call. + * + * @param response response to be provided to the call + * @param index index of the callback within the arguments + * @return a function that provides the response to the call + */ + protected Answer> provideResponse(Response response, int index) { + return args -> { + InvocationCallback cb = args.getArgument(index); + cb.completed(response); + return CompletableFuture.completedFuture(response); + }; + } + + private static class MyOper extends HttpOperation { + + public MyOper(ControlLoopOperationParams params, HttpConfig config) { + super(params, config, String.class); + + setUsePolling(); + } + + @Override + protected Status detmStatus(Response rawResponse, String response) { + switch (rawResponse.getStatus()) { + case RESPONSE_ACCEPT: + return Status.STILL_WAITING; + case RESPONSE_SUCCESS: + return Status.SUCCESS; + default: + return Status.FAILURE; + } + } + + @Override + protected boolean isSuccess(Response rawResponse, String response) { + return true; + } + } +} diff --git a/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperatorTest.java b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperatorTest.java new file mode 100644 index 000000000..2a22b4b86 --- /dev/null +++ b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/impl/HttpPollingOperatorTest.java @@ -0,0 +1,117 @@ +/*- + * ============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.actorserviceprovider.impl; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingParams; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException; + +public class HttpPollingOperatorTest { + private static final String ACTOR = "my-actor"; + private static final String OPERATION = "my-name"; + private static final String CLIENT = "my-client"; + private static final String PATH = "/my-path"; + private static final String POLL_PATH = "my-path-get/"; + private static final int MAX_POLLS = 3; + private static final int POLL_WAIT_SEC = 20; + private static final int TIMEOUT = 100; + + @Mock + private HttpClient client; + @Mock + private HttpClientFactory factory; + + private HttpPollingOperator oper; + + /** + * Initializes fields, including {@link #oper}, and resets the static fields used by + * the REST server. + */ + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + when(factory.get(CLIENT)).thenReturn(client); + + oper = new MyOperator(); + + HttpPollingParams params = HttpPollingParams.builder().pollPath(POLL_PATH).maxPolls(MAX_POLLS) + .pollWaitSec(POLL_WAIT_SEC).clientName(CLIENT).path(PATH).timeoutSec(TIMEOUT).build(); + Map paramMap = Util.translateToMap(OPERATION, params); + oper.configure(paramMap); + } + + @Test + public void testConstructor() { + assertEquals(ACTOR, oper.getActorName()); + assertEquals(OPERATION, oper.getName()); + assertEquals(ACTOR + "." + OPERATION, oper.getFullName()); + } + + @Test + public void testDoConfigure_testGetters() { + assertTrue(oper.getCurrentConfig() instanceof HttpPollingConfig); + + // test invalid parameters + Map paramMap2 = Util.translateToMap(OPERATION, HttpPollingParams.builder().build()); + assertThatThrownBy(() -> oper.configure(paramMap2)).isInstanceOf(ParameterValidationRuntimeException.class); + } + + @Test + public void testGetClientFactory() { + HttpPollingOperator oper2 = new HttpPollingOperator(ACTOR, OPERATION); + assertNotNull(oper2.getClientFactory()); + } + + + private class MyOperator extends HttpPollingOperator { + public MyOperator() { + super(ACTOR, OPERATION, MyOperation::new); + } + + @Override + protected HttpClientFactory getClientFactory() { + return factory; + } + } + + private static class MyOperation extends HttpOperation { + public MyOperation(ControlLoopOperationParams params, HttpConfig config) { + super(params, config, String.class); + } + } +} diff --git a/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingActorParamsTest.java b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingActorParamsTest.java new file mode 100644 index 000000000..78240beb6 --- /dev/null +++ b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingActorParamsTest.java @@ -0,0 +1,118 @@ +/*- + * ============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.actorserviceprovider.parameters; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Map; +import java.util.TreeMap; +import java.util.function.Consumer; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ActorParams; + + +public class HttpPollingActorParamsTest { + private static final String CONTAINER = "my-container"; + private static final String CLIENT = "my-client"; + private static final String POLL_PATH = "my-poll-path"; + private static final int MAX_POLLS = 3; + private static final int POLL_WAIT_SEC = 20; + private static final int TIMEOUT = 10; + + private static final String PATH1 = "path #1"; + private static final String PATH2 = "path #2"; + private static final String URI1 = "uri #1"; + private static final String URI2 = "uri #2"; + + private Map> operations; + private HttpPollingActorParams params; + + /** + * Initializes {@link #operations} with two items and {@link params} with a fully + * populated object. + */ + @Before + public void setUp() { + operations = new TreeMap<>(); + operations.put(PATH1, Map.of("path", URI1)); + operations.put(PATH2, Map.of("path", URI2)); + + params = makeHttpPollingActorParams(); + } + + @Test + public void testValidate() { + assertTrue(params.validate(CONTAINER).isValid()); + + // only a few fields are required + HttpPollingActorParams sparse = Util.translate(CONTAINER, Map.of(ActorParams.OPERATIONS_FIELD, operations), + HttpPollingActorParams.class); + assertTrue(sparse.validate(CONTAINER).isValid()); + + testValidateField("maxPolls", "minimum", params2 -> params2.setMaxPolls(-1)); + testValidateField("pollWaitSec", "minimum", params2 -> params2.setPollWaitSec(0)); + + // check fields from superclass + testValidateField(ActorParams.OPERATIONS_FIELD, "null", params2 -> params2.setOperations(null)); + testValidateField("timeoutSec", "minimum", params2 -> params2.setTimeoutSec(-1)); + + // check edge cases + params.setMaxPolls(0); + assertTrue(params.validate(CONTAINER).isValid()); + params.setMaxPolls(MAX_POLLS); + + params.setPollWaitSec(1); + assertTrue(params.validate(CONTAINER).isValid()); + params.setPollWaitSec(POLL_WAIT_SEC); + } + + private void testValidateField(String fieldName, String expected, Consumer makeInvalid) { + + // original params should be valid + ValidationResult result = params.validate(CONTAINER); + assertTrue(fieldName, result.isValid()); + + // make invalid params + HttpPollingActorParams params2 = makeHttpPollingActorParams(); + makeInvalid.accept(params2); + result = params2.validate(CONTAINER); + assertFalse(fieldName, result.isValid()); + assertThat(result.getResult()).contains(CONTAINER).contains(fieldName).contains(expected); + } + + private HttpPollingActorParams makeHttpPollingActorParams() { + HttpPollingActorParams params2 = new HttpPollingActorParams(); + params2.setClientName(CLIENT); + params2.setTimeoutSec(TIMEOUT); + params2.setOperations(operations); + + params2.setPollWaitSec(POLL_WAIT_SEC); + params2.setMaxPolls(MAX_POLLS); + params2.setPollPath(POLL_PATH); + + return params2; + } +} diff --git a/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingConfigTest.java b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingConfigTest.java new file mode 100644 index 000000000..53be6c711 --- /dev/null +++ b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingConfigTest.java @@ -0,0 +1,82 @@ +/*- + * ============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.actorserviceprovider.parameters; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.when; + +import java.util.concurrent.Executor; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; + +public class HttpPollingConfigTest { + private static final String MY_CLIENT = "my-client"; + private static final String MY_PATH = "my-path"; + private static final String POLL_PATH = "poll-path"; + private static final int TIMEOUT_SEC = 10; + private static final int MAX_POLLS = 20; + private static final int WAIT_SEC = 30; + + @Mock + private HttpClient client; + @Mock + private HttpClientFactory factory; + @Mock + private Executor executor; + + private HttpPollingParams params; + private HttpPollingConfig config; + + /** + * Sets up. + */ + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + when(factory.get(MY_CLIENT)).thenReturn(client); + + params = HttpPollingParams.builder().maxPolls(MAX_POLLS).pollPath(POLL_PATH).pollWaitSec(WAIT_SEC) + .clientName(MY_CLIENT).path(MY_PATH).timeoutSec(TIMEOUT_SEC).build(); + config = new HttpPollingConfig(executor, params, factory); + } + + @Test + public void test() { + assertEquals(POLL_PATH + "/", config.getPollPath()); + assertEquals(MAX_POLLS, config.getMaxPolls()); + assertEquals(WAIT_SEC, config.getPollWaitSec()); + + // check value from superclass + assertSame(executor, config.getBlockingExecutor()); + assertSame(client, config.getClient()); + + // path with trailing "/" + params = params.toBuilder().pollPath(POLL_PATH + "/").build(); + config = new HttpPollingConfig(executor, params, factory); + assertEquals(POLL_PATH + "/", config.getPollPath()); + } +} diff --git a/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingParamsTest.java b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingParamsTest.java new file mode 100644 index 000000000..e3fef83c5 --- /dev/null +++ b/models-interactions/model-actors/actorServiceProvider/src/test/java/org/onap/policy/controlloop/actorserviceprovider/parameters/HttpPollingParamsTest.java @@ -0,0 +1,91 @@ +/*- + * ============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.actorserviceprovider.parameters; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.function.Function; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingParams.HttpPollingParamsBuilder; + +public class HttpPollingParamsTest { + private static final String CONTAINER = "my-container"; + private static final String CLIENT = "my-client"; + private static final String PATH = "my-path"; + private static final String POLL_PATH = "my-poll-path"; + private static final int MAX_POLLS = 3; + private static final int POLL_WAIT_SEC = 20; + private static final int TIMEOUT = 10; + + private HttpPollingParams params; + + @Before + public void setUp() { + params = HttpPollingParams.builder().pollPath(POLL_PATH).maxPolls(MAX_POLLS).pollWaitSec(POLL_WAIT_SEC) + .clientName(CLIENT).path(PATH).timeoutSec(TIMEOUT).build(); + } + + @Test + public void testValidate() { + assertTrue(params.validate(CONTAINER).isValid()); + + testValidateField("pollPath", "null", bldr -> bldr.pollPath(null)); + testValidateField("maxPolls", "minimum", bldr -> bldr.maxPolls(-1)); + testValidateField("pollWaitSec", "minimum", bldr -> bldr.pollWaitSec(-1)); + + // validate one of the superclass fields + testValidateField("clientName", "null", bldr -> bldr.clientName(null)); + + // check edge cases + assertTrue(params.toBuilder().maxPolls(0).build().validate(CONTAINER).isValid()); + assertFalse(params.toBuilder().pollWaitSec(0).build().validate(CONTAINER).isValid()); + assertTrue(params.toBuilder().pollWaitSec(1).build().validate(CONTAINER).isValid()); + } + + @Test + public void testBuilder_testToBuilder() { + assertEquals(CLIENT, params.getClientName()); + + assertEquals(POLL_PATH, params.getPollPath()); + assertEquals(MAX_POLLS, params.getMaxPolls()); + assertEquals(POLL_WAIT_SEC, params.getPollWaitSec()); + + assertEquals(params, params.toBuilder().build()); + } + + private void testValidateField(String fieldName, String expected, + Function, HttpPollingParamsBuilder> makeInvalid) { + + // original params should be valid + ValidationResult result = params.validate(CONTAINER); + assertTrue(fieldName, result.isValid()); + + // make invalid params + result = makeInvalid.apply(params.toBuilder()).build().validate(CONTAINER); + assertFalse(fieldName, result.isValid()); + assertThat(result.getResult()).contains(fieldName).contains(expected); + } +} -- cgit 1.2.3-korg