From 988f2af648a069ae86a4d9fc9499b80716ca8443 Mon Sep 17 00:00:00 2001 From: ecaiyanlinux Date: Tue, 27 Oct 2020 20:40:57 +0100 Subject: Remove code for sdnc onap controller sdnc onap controller is dismissed rename SdncOscA1Client to CcsdkA1AdapterClient rename SdncJsonHelper to A1AdapterJsonHelper update comments accordingly Signed-off-by: ecaiyanlinux Issue-ID: CCSDK-2502 Change-Id: If525dab599f9fd28203e85dcd57c010c67e20a8b --- .../clients/A1AdapterJsonHelper.java | 119 ++++++ .../clients/A1Client.java | 7 +- .../clients/A1ClientFactory.java | 11 +- .../clients/CcsdkA1AdapterClient.java | 304 +++++++++++++++ .../clients/OscA1Client.java | 4 +- .../clients/SdncJsonHelper.java | 119 ------ .../clients/SdncOnapA1Client.java | 194 ---------- .../clients/SdncOscA1Client.java | 304 --------------- .../clients/StdA1ClientVersion1.java | 2 +- .../clients/StdA1ClientVersion2.java | 4 +- .../clients/A1ClientFactoryTest.java | 5 +- .../clients/CcsdkA1AdapterClientTest.java | 414 +++++++++++++++++++++ .../clients/SdncOnapA1ClientTest.java | 271 -------------- .../clients/SdncOscA1ClientTest.java | 414 --------------------- 14 files changed, 851 insertions(+), 1321 deletions(-) create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1AdapterJsonHelper.java create mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/CcsdkA1AdapterClient.java delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncJsonHelper.java delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1Client.java delete mode 100644 a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1Client.java create mode 100644 a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/CcsdkA1AdapterClientTest.java delete mode 100644 a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1ClientTest.java delete mode 100644 a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1ClientTest.java diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1AdapterJsonHelper.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1AdapterJsonHelper.java new file mode 100644 index 00000000..c72f196a --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1AdapterJsonHelper.java @@ -0,0 +1,119 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.clients; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.invoke.MethodHandles; +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Common json functionality used by the CCSDK A1 Adapter clients + */ +@SuppressWarnings("java:S1192") // Same text in several traces +class A1AdapterJsonHelper { + private static Gson gson = new GsonBuilder() // + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) // + .create(); + private static final String OUTPUT = "output"; + private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + + private A1AdapterJsonHelper() {} + + public static Flux parseJsonArrayOfString(String inputString) { + try { + List arrayList = new ArrayList<>(); + if (!inputString.isEmpty()) { + JSONArray jsonArray = new JSONArray(inputString); + for (int i = 0; i < jsonArray.length(); i++) { + Object value = jsonArray.get(i); + arrayList.add(value.toString()); + } + } + return Flux.fromIterable(arrayList); + } catch (JSONException ex) { // invalid json + logger.debug("Invalid json {}", ex.getMessage()); + return Flux.error(ex); + } + } + + public static String createInputJsonString(T params) { + JsonElement paramsJson = gson.toJsonTree(params); + JsonObject jsonObj = new JsonObject(); + jsonObj.add("input", paramsJson); + return gson.toJson(jsonObj); + } + + public static String createOutputJsonString(T params) { + JsonElement paramsJson = gson.toJsonTree(params); + JsonObject jsonObj = new JsonObject(); + jsonObj.add(OUTPUT, paramsJson); + return gson.toJson(jsonObj); + } + + public static Mono getOutput(String response) { + try { + JSONObject outputJson = new JSONObject(response); + JSONObject responseParams = outputJson.getJSONObject(OUTPUT); + return Mono.just(responseParams); + } catch (JSONException ex) { // invalid json + logger.debug("Invalid json {}", ex.getMessage()); + return Mono.error(ex); + } + } + + public static Mono getValueFromResponse(String response, String key) { + return getOutput(response) // + .flatMap(responseParams -> { + if (!responseParams.has(key)) { + return Mono.just(""); + } + String value = responseParams.get(key).toString(); + return Mono.just(value); + }); + } + + public static Mono extractPolicySchema(String inputString) { + try { + JSONObject jsonObject = new JSONObject(inputString); + JSONObject schemaObject = jsonObject.getJSONObject("policySchema"); + String schemaString = schemaObject.toString(); + return Mono.just(schemaString); + } catch (JSONException ex) { // invalid json + logger.debug("Invalid json {}", ex.getMessage()); + return Mono.error(ex); + } + } +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1Client.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1Client.java index 4321ed48..5e498e4b 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1Client.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1Client.java @@ -38,10 +38,9 @@ public interface A1Client { STD_V1_1, // STD A1 version 1.1 STD_V2_0_0, // STD A1 version 2.0.0 OSC_V1, // OSC 'A1' - SDNC_OSC_STD_V1_1, // SDNC_OSC with STD A1 version 1.1 southbound - SDNC_OSC_STD_V2_0_0, // SDNC_OSC with STD A1 version 2.0.0 southbound - SDNC_OSC_OSC_V1, // SDNC_OSC with OSC 'A1' southbound - SDNC_ONAP + CCSDK_A1_ADAPTER_STD_V1_1, // CCSDK_A1_ADAPTER with STD A1 version 1.1 southbound + CCSDK_A1_ADAPTER_STD_V2_0_0, // CCSDK_A1_ADAPTER with STD A1 version 2.0.0 southbound + CCSDK_A1_ADAPTER_OSC_V1 // CCSDK_A1_ADAPTER with OSC 'A1' southbound } public Mono getProtocolVersion(); diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactory.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactory.java index 66ba60c0..0ca3a45d 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactory.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactory.java @@ -79,11 +79,9 @@ public class A1ClientFactory { } else if (version == A1ProtocolType.OSC_V1) { assertNoControllerConfig(ric, version); return new OscA1Client(ric.getConfig(), this.restClientFactory); - } else if (version == A1ProtocolType.SDNC_OSC_STD_V1_1 || version == A1ProtocolType.SDNC_OSC_OSC_V1 - || version == A1ProtocolType.SDNC_OSC_STD_V2_0_0) { - return new SdncOscA1Client(version, ric.getConfig(), getControllerConfig(ric), this.restClientFactory); - } else if (version == A1ProtocolType.SDNC_ONAP) { - return new SdncOnapA1Client(ric.getConfig(), getControllerConfig(ric), this.restClientFactory); + } else if (version == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1 || version == A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1 + || version == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0) { + return new CcsdkA1AdapterClient(version, ric.getConfig(), getControllerConfig(ric), this.restClientFactory); } else { logger.error("Unhandled protocol: {}", version); throw new ServiceException("Unhandled protocol"); @@ -125,8 +123,7 @@ public class A1ClientFactory { return fetchVersion(ric, A1ProtocolType.STD_V2_0_0) // .onErrorResume(notUsed -> fetchVersion(ric, A1ProtocolType.STD_V1_1)) // .onErrorResume(notUsed -> fetchVersion(ric, A1ProtocolType.OSC_V1)) // - .onErrorResume(notUsed -> fetchVersion(ric, A1ProtocolType.SDNC_OSC_STD_V1_1)) // - .onErrorResume(notUsed -> fetchVersion(ric, A1ProtocolType.SDNC_ONAP)) // + .onErrorResume(notUsed -> fetchVersion(ric, A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1)) // .doOnNext(ric::setProtocolVersion) .doOnNext(version -> logger.debug("Established protocol version:{} for Near-RT RIC: {}", version, ric.id())) // diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/CcsdkA1AdapterClient.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/CcsdkA1AdapterClient.java new file mode 100644 index 00000000..3b581b63 --- /dev/null +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/CcsdkA1AdapterClient.java @@ -0,0 +1,304 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.clients; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.GsonBuilder; + +import java.lang.invoke.MethodHandles; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.immutables.value.Value; +import org.json.JSONObject; +import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ControllerConfig; +import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.WebClientResponseException; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +/** + * Client for accessing the A1 adapter in the CCSDK in ONAP. + */ +@SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally +public class CcsdkA1AdapterClient implements A1Client { + + static final int CONCURRENCY_RIC = 1; // How many paralell requests that is sent to one NearRT RIC + + @Value.Immutable + @org.immutables.gson.Gson.TypeAdapters + public interface AdapterRequest { + public String nearRtRicUrl(); + + public Optional body(); + } + + @Value.Immutable + @org.immutables.gson.Gson.TypeAdapters + public interface AdapterOutput { + public Optional body(); + + public int httpStatus(); + } + + static com.google.gson.Gson gson = new GsonBuilder() // + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) // + .create(); // + + private static final String GET_POLICY_RPC = "getA1Policy"; + private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); + private final ControllerConfig controllerConfig; + private final AsyncRestClient restClient; + private final RicConfig ricConfig; + private final A1ProtocolType protocolType; + + /** + * Constructor that creates the REST client to use. + * + * @param protocolType the southbound protocol of the controller. Supported + * protocols are CCSDK_A1_ADAPTER_STD_V1_1, CCSDK_A1_ADAPTER_OSC_V1 and + * CCSDK_A1_ADAPTER_STD_V2_0_0 with + * @param ricConfig the configuration of the Near-RT RIC to communicate + * with + * @param controllerConfig the configuration of the CCSDK A1 Adapter to use + * + * @throws IllegalArgumentException when the protocolType is wrong. + */ + public CcsdkA1AdapterClient(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig, + AsyncRestClientFactory restClientFactory) { + this(protocolType, ricConfig, controllerConfig, + restClientFactory.createRestClient(controllerConfig.baseUrl() + "/restconf/operations")); + } + + /** + * Constructor where the REST client to use is provided. + * + * @param protocolType the southbound protocol of the controller. Supported + * protocols are CCSDK_A1_ADAPTER_STD_V1_1, CCSDK_A1_ADAPTER_OSC_V1 and + * CCSDK_A1_ADAPTER_STD_V2_0_0 with + * @param ricConfig the configuration of the Near-RT RIC to communicate + * with + * @param controllerConfig the configuration of the CCSDK A1 Adapter to use + * @param restClient the REST client to use + * + * @throws IllegalArgumentException when the protocolType is illegal. + */ + public CcsdkA1AdapterClient(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig, + AsyncRestClient restClient) { + if (A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1.equals(protocolType) // + || A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1.equals(protocolType) // + || A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0.equals(protocolType)) { + this.restClient = restClient; + this.ricConfig = ricConfig; + this.protocolType = protocolType; + this.controllerConfig = controllerConfig; + logger.debug("CcsdkA1AdapterClient for ric: {}, a1Controller: {}", ricConfig.ricId(), controllerConfig); + } else { + throw new IllegalArgumentException("Not handeled protocolversion: " + protocolType); + } + + } + + @Override + public Mono> getPolicyTypeIdentities() { + if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) { + return Mono.just(Arrays.asList("")); + } else { + return post(GET_POLICY_RPC, getUriBuilder().createPolicyTypesUri(), Optional.empty()) // + .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString) // + .collectList(); + } + + } + + @Override + public Mono> getPolicyIdentities() { + return getPolicyIds() // + .collectList(); + } + + @Override + public Mono getPolicyTypeSchema(String policyTypeId) { + if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) { + return Mono.just("{}"); + } else { + A1UriBuilder uri = this.getUriBuilder(); + final String ricUrl = uri.createGetSchemaUri(policyTypeId); + return post(GET_POLICY_RPC, ricUrl, Optional.empty()) // + .flatMap(response -> extractCreateSchema(response, policyTypeId)); + } + } + + private Mono extractCreateSchema(String controllerResponse, String policyTypeId) { + if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1) { + return OscA1Client.extractCreateSchema(controllerResponse, policyTypeId); + } else if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0) { + return StdA1ClientVersion2.extractPolicySchema(controllerResponse, policyTypeId); + } else { + throw new NullPointerException("Not supported"); + } + } + + @Override + public Mono putPolicy(Policy policy) { + String ricUrl = + getUriBuilder().createPutPolicyUri(policy.type().id(), policy.id(), policy.statusNotificationUri()); + return post("putA1Policy", ricUrl, Optional.of(policy.json())); + } + + @Override + public Mono deletePolicy(Policy policy) { + return deletePolicyById(policy.type().id(), policy.id()); + } + + @Override + public Flux deleteAllPolicies() { + if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) { + return getPolicyIds() // + .flatMap(policyId -> deletePolicyById("", policyId), CONCURRENCY_RIC); // + } else { + A1UriBuilder uriBuilder = this.getUriBuilder(); + return getPolicyTypeIdentities() // + .flatMapMany(Flux::fromIterable) // + .flatMap(type -> deleteAllInstancesForType(uriBuilder, type), CONCURRENCY_RIC); + } + } + + private Flux getInstancesForType(A1UriBuilder uriBuilder, String type) { + return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(type), Optional.empty()) // + .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString); + } + + private Flux deleteAllInstancesForType(A1UriBuilder uriBuilder, String type) { + return getInstancesForType(uriBuilder, type) // + .flatMap(instance -> deletePolicyById(type, instance), CONCURRENCY_RIC); + } + + @Override + public Mono getProtocolVersion() { + return tryStdProtocolVersion2() // + .onErrorResume(t -> tryStdProtocolVersion1()) // + .onErrorResume(t -> tryOscProtocolVersion()); + } + + @Override + public Mono getPolicyStatus(Policy policy) { + String ricUrl = getUriBuilder().createGetPolicyStatusUri(policy.type().id(), policy.id()); + return post("getA1PolicyStatus", ricUrl, Optional.empty()); + + } + + private A1UriBuilder getUriBuilder() { + if (protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) { + return new StdA1ClientVersion1.UriBuilder(ricConfig); + } else if (protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0) { + return new StdA1ClientVersion2.OranV2UriBuilder(ricConfig); + } else if (protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1) { + return new OscA1Client.UriBuilder(ricConfig); + } + throw new NullPointerException(); + } + + private Mono tryOscProtocolVersion() { + OscA1Client.UriBuilder oscApiuriBuilder = new OscA1Client.UriBuilder(ricConfig); + return post(GET_POLICY_RPC, oscApiuriBuilder.createHealtcheckUri(), Optional.empty()) // + .flatMap(x -> Mono.just(A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1)); + } + + private Mono tryStdProtocolVersion1() { + StdA1ClientVersion1.UriBuilder uriBuilder = new StdA1ClientVersion1.UriBuilder(ricConfig); + return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(""), Optional.empty()) // + .flatMap(x -> Mono.just(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1)); + } + + private Mono tryStdProtocolVersion2() { + StdA1ClientVersion2.OranV2UriBuilder uriBuilder = new StdA1ClientVersion2.OranV2UriBuilder(ricConfig); + return post(GET_POLICY_RPC, uriBuilder.createPolicyTypesUri(), Optional.empty()) // + .flatMap(x -> Mono.just(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0)); + } + + private Flux getPolicyIds() { + if (this.protocolType == A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) { + StdA1ClientVersion1.UriBuilder uri = new StdA1ClientVersion1.UriBuilder(ricConfig); + final String ricUrl = uri.createGetPolicyIdsUri(""); + return post(GET_POLICY_RPC, ricUrl, Optional.empty()) // + .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString); + } else { + A1UriBuilder uri = this.getUriBuilder(); + return getPolicyTypeIdentities() // + .flatMapMany(Flux::fromIterable) + .flatMap(type -> post(GET_POLICY_RPC, uri.createGetPolicyIdsUri(type), Optional.empty())) // + .flatMap(A1AdapterJsonHelper::parseJsonArrayOfString); + } + } + + private Mono deletePolicyById(String type, String policyId) { + String ricUrl = getUriBuilder().createDeleteUri(type, policyId); + return post("deleteA1Policy", ricUrl, Optional.empty()); + } + + private Mono post(String rpcName, String ricUrl, Optional body) { + AdapterRequest inputParams = ImmutableAdapterRequest.builder() // + .nearRtRicUrl(ricUrl) // + .body(body) // + .build(); + final String inputJsonString = A1AdapterJsonHelper.createInputJsonString(inputParams); + logger.debug("POST inputJsonString = {}", inputJsonString); + + return restClient + .postWithAuthHeader(controllerUrl(rpcName), inputJsonString, this.controllerConfig.userName(), + this.controllerConfig.password()) // + .flatMap(this::extractResponseBody); + } + + private Mono extractResponse(JSONObject responseOutput) { + AdapterOutput output = gson.fromJson(responseOutput.toString(), ImmutableAdapterOutput.class); + Optional optionalBody = output.body(); + String body = optionalBody.isPresent() ? optionalBody.get() : ""; + if (HttpStatus.valueOf(output.httpStatus()).is2xxSuccessful()) { + return Mono.just(body); + } else { + logger.debug("Error response: {} {}", output.httpStatus(), body); + byte[] responseBodyBytes = body.getBytes(StandardCharsets.UTF_8); + HttpStatus httpStatus = HttpStatus.valueOf(output.httpStatus()); + WebClientResponseException responseException = new WebClientResponseException(httpStatus.value(), + httpStatus.getReasonPhrase(), null, responseBodyBytes, StandardCharsets.UTF_8, null); + + return Mono.error(responseException); + } + } + + private Mono extractResponseBody(String responseStr) { + return A1AdapterJsonHelper.getOutput(responseStr) // + .flatMap(this::extractResponse); + } + + private String controllerUrl(String rpcName) { + return "/A1-ADAPTER-API:" + rpcName; + } +} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/OscA1Client.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/OscA1Client.java index f54dc2e0..402a73b4 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/OscA1Client.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/OscA1Client.java @@ -195,12 +195,12 @@ public class OscA1Client implements A1Client { private Flux getPolicyTypeIds() { return restClient.get(uri.createPolicyTypesUri()) // - .flatMapMany(SdncJsonHelper::parseJsonArrayOfString); + .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString); } private Flux getPolicyIdentitiesByType(String typeId) { return restClient.get(uri.createGetPolicyIdsUri(typeId)) // - .flatMapMany(SdncJsonHelper::parseJsonArrayOfString); + .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString); } private Mono deletePolicyById(String typeId, String policyId) { diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncJsonHelper.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncJsonHelper.java deleted file mode 100644 index ada35fd6..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncJsonHelper.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.clients; - -import com.google.gson.FieldNamingPolicy; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.lang.invoke.MethodHandles; -import java.util.ArrayList; -import java.util.List; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Common json functionality used by the SDNC clients - */ -@SuppressWarnings("java:S1192") // Same text in several traces -class SdncJsonHelper { - private static Gson gson = new GsonBuilder() // - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) // - .create(); - private static final String OUTPUT = "output"; - private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - - private SdncJsonHelper() {} - - public static Flux parseJsonArrayOfString(String inputString) { - try { - List arrayList = new ArrayList<>(); - if (!inputString.isEmpty()) { - JSONArray jsonArray = new JSONArray(inputString); - for (int i = 0; i < jsonArray.length(); i++) { - Object value = jsonArray.get(i); - arrayList.add(value.toString()); - } - } - return Flux.fromIterable(arrayList); - } catch (JSONException ex) { // invalid json - logger.debug("Invalid json {}", ex.getMessage()); - return Flux.error(ex); - } - } - - public static String createInputJsonString(T params) { - JsonElement paramsJson = gson.toJsonTree(params); - JsonObject jsonObj = new JsonObject(); - jsonObj.add("input", paramsJson); - return gson.toJson(jsonObj); - } - - public static String createOutputJsonString(T params) { - JsonElement paramsJson = gson.toJsonTree(params); - JsonObject jsonObj = new JsonObject(); - jsonObj.add(OUTPUT, paramsJson); - return gson.toJson(jsonObj); - } - - public static Mono getOutput(String response) { - try { - JSONObject outputJson = new JSONObject(response); - JSONObject responseParams = outputJson.getJSONObject(OUTPUT); - return Mono.just(responseParams); - } catch (JSONException ex) { // invalid json - logger.debug("Invalid json {}", ex.getMessage()); - return Mono.error(ex); - } - } - - public static Mono getValueFromResponse(String response, String key) { - return getOutput(response) // - .flatMap(responseParams -> { - if (!responseParams.has(key)) { - return Mono.just(""); - } - String value = responseParams.get(key).toString(); - return Mono.just(value); - }); - } - - public static Mono extractPolicySchema(String inputString) { - try { - JSONObject jsonObject = new JSONObject(inputString); - JSONObject schemaObject = jsonObject.getJSONObject("policySchema"); - String schemaString = schemaObject.toString(); - return Mono.just(schemaString); - } catch (JSONException ex) { // invalid json - logger.debug("Invalid json {}", ex.getMessage()); - return Mono.error(ex); - } - } -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1Client.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1Client.java deleted file mode 100644 index 68b0ab18..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1Client.java +++ /dev/null @@ -1,194 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.clients; - -import java.lang.invoke.MethodHandles; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import org.immutables.gson.Gson; -import org.immutables.value.Value; -import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ControllerConfig; -import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Client for accessing the A1 adapter in the SDNC controller in ONAP - */ -@SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally -public class SdncOnapA1Client implements A1Client { - @Value.Immutable - @Gson.TypeAdapters - interface SdncOnapAdapterInput { - public String nearRtRicId(); - - public Optional policyTypeId(); - - public Optional policyInstanceId(); - - public Optional policyInstance(); - - public Optional> properties(); - } - - private static final String URL_PREFIX = "/A1-ADAPTER-API:"; - - private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - - private final ControllerConfig controllerConfig; - private final RicConfig ricConfig; - private final AsyncRestClient restClient; - - public SdncOnapA1Client(RicConfig ricConfig, ControllerConfig controllerConfig, - AsyncRestClientFactory restClientFactory) { - this(ricConfig, controllerConfig, - restClientFactory.createRestClient(controllerConfig.baseUrl() + "/restconf/operations")); - logger.debug("SdncOnapA1Client for ric: {}, a1ControllerBaseUrl: {}", ricConfig.ricId(), - controllerConfig.baseUrl()); - } - - public SdncOnapA1Client(RicConfig ricConfig, ControllerConfig controllerConfig, AsyncRestClient restClient) { - this.ricConfig = ricConfig; - this.controllerConfig = controllerConfig; - this.restClient = restClient; - } - - @Override - public Mono> getPolicyTypeIdentities() { - return getPolicyTypeIds() // - .collectList(); - } - - @Override - public Mono> getPolicyIdentities() { - return getPolicyTypeIds() // - .flatMap(this::getPolicyIdentitiesByType) // - .collectList(); - } - - @Override - public Mono getPolicyTypeSchema(String policyTypeId) { - SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(ricConfig.baseUrl()) // - .policyTypeId(policyTypeId) // - .build(); - String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - logger.debug("POST getPolicyType inputJsonString = {}", inputJsonString); - - return restClient - .postWithAuthHeader(URL_PREFIX + "getPolicyType", inputJsonString, controllerConfig.userName(), - controllerConfig.password()) // - .flatMap(response -> SdncJsonHelper.getValueFromResponse(response, "policy-type")) // - .flatMap(SdncJsonHelper::extractPolicySchema); - } - - @Override - public Mono putPolicy(Policy policy) { - SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(ricConfig.baseUrl()) // - .policyTypeId(policy.type().id()) // - .policyInstanceId(policy.id()) // - .policyInstance(policy.json()) // - .properties(new ArrayList<>()) // - .build(); - - String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - logger.debug("POST putPolicy inputJsonString = {}", inputJsonString); - - return restClient.postWithAuthHeader(URL_PREFIX + "createPolicyInstance", inputJsonString, - controllerConfig.userName(), controllerConfig.password()); - } - - @Override - public Mono deletePolicy(Policy policy) { - return deletePolicyByTypeId(policy.type().id(), policy.id()); - } - - @Override - public Flux deleteAllPolicies() { - return getPolicyTypeIds() // - .flatMap(this::deletePoliciesForType); // - } - - @Override - public Mono getProtocolVersion() { - return getPolicyTypeIdentities() // - .flatMap(notUsed -> Mono.just(A1ProtocolType.SDNC_ONAP)); - } - - @Override - public Mono getPolicyStatus(Policy policy) { - return Mono.error(new Exception("Status not implemented in the controller")); - } - - private Flux getPolicyTypeIds() { - SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(ricConfig.baseUrl()) // - .build(); - String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - logger.debug("POST getPolicyTypeIdentities inputJsonString = {}", inputJsonString); - - return restClient - .postWithAuthHeader(URL_PREFIX + "getPolicyTypes", inputJsonString, controllerConfig.userName(), - controllerConfig.password()) // - .flatMap(response -> SdncJsonHelper.getValueFromResponse(response, "policy-type-id-list")) // - .flatMapMany(SdncJsonHelper::parseJsonArrayOfString); - } - - private Flux getPolicyIdentitiesByType(String policyTypeId) { - SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(ricConfig.baseUrl()) // - .policyTypeId(policyTypeId) // - .build(); - String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - logger.debug("POST getPolicyIdentities inputJsonString = {}", inputJsonString); - - return restClient - .postWithAuthHeader(URL_PREFIX + "getPolicyInstances", inputJsonString, controllerConfig.userName(), - controllerConfig.password()) // - .flatMap(response -> SdncJsonHelper.getValueFromResponse(response, "policy-instance-id-list")) // - .flatMapMany(SdncJsonHelper::parseJsonArrayOfString); - } - - private Flux deletePoliciesForType(String typeId) { - return getPolicyIdentitiesByType(typeId) // - .flatMap(policyId -> deletePolicyByTypeId(typeId, policyId)); // - } - - private Mono deletePolicyByTypeId(String policyTypeId, String policyId) { - SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(ricConfig.baseUrl()) // - .policyTypeId(policyTypeId) // - .policyInstanceId(policyId) // - .build(); - String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - logger.debug("POST deletePolicy inputJsonString = {}", inputJsonString); - - return restClient.postWithAuthHeader(URL_PREFIX + "deletePolicyInstance", inputJsonString, - controllerConfig.userName(), controllerConfig.password()); - } -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1Client.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1Client.java deleted file mode 100644 index 88859d37..00000000 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1Client.java +++ /dev/null @@ -1,304 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.clients; - -import com.google.gson.FieldNamingPolicy; -import com.google.gson.GsonBuilder; - -import java.lang.invoke.MethodHandles; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import org.immutables.value.Value; -import org.json.JSONObject; -import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ControllerConfig; -import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.web.reactive.function.client.WebClientResponseException; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; - -/** - * Client for accessing the A1 adapter in the SDNC controller in OSC. - */ -@SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally -public class SdncOscA1Client implements A1Client { - - static final int CONCURRENCY_RIC = 1; // How many paralell requests that is sent to one NearRT RIC - - @Value.Immutable - @org.immutables.gson.Gson.TypeAdapters - public interface AdapterRequest { - public String nearRtRicUrl(); - - public Optional body(); - } - - @Value.Immutable - @org.immutables.gson.Gson.TypeAdapters - public interface AdapterOutput { - public Optional body(); - - public int httpStatus(); - } - - static com.google.gson.Gson gson = new GsonBuilder() // - .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) // - .create(); // - - private static final String GET_POLICY_RPC = "getA1Policy"; - private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); - private final ControllerConfig controllerConfig; - private final AsyncRestClient restClient; - private final RicConfig ricConfig; - private final A1ProtocolType protocolType; - - /** - * Constructor that creates the REST client to use. - * - * @param protocolType the southbound protocol of the controller. Supported - * protocols are SDNC_OSC_STD_V1_1, SDNC_OSC_OSC_V1 and - * SDNC_OSC_STD_V2_0_0 with - * @param ricConfig the configuration of the Near-RT RIC to communicate - * with - * @param controllerConfig the configuration of the SDNC controller to use - * - * @throws IllegalArgumentException when the protocolType is wrong. - */ - public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig, - AsyncRestClientFactory restClientFactory) { - this(protocolType, ricConfig, controllerConfig, - restClientFactory.createRestClient(controllerConfig.baseUrl() + "/restconf/operations")); - } - - /** - * Constructor where the REST client to use is provided. - * - * @param protocolType the southbound protocol of the controller. Supported - * protocols are SDNC_OSC_STD_V1_1, SDNC_OSC_OSC_V1 and - * SDNC_OSC_STD_V2_0_0 with - * @param ricConfig the configuration of the Near-RT RIC to communicate - * with - * @param controllerConfig the configuration of the SDNC controller to use - * @param restClient the REST client to use - * - * @throws IllegalArgumentException when the protocolType is illegal. - */ - public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, ControllerConfig controllerConfig, - AsyncRestClient restClient) { - if (A1ProtocolType.SDNC_OSC_STD_V1_1.equals(protocolType) // - || A1ProtocolType.SDNC_OSC_OSC_V1.equals(protocolType) // - || A1ProtocolType.SDNC_OSC_STD_V2_0_0.equals(protocolType)) { - this.restClient = restClient; - this.ricConfig = ricConfig; - this.protocolType = protocolType; - this.controllerConfig = controllerConfig; - logger.debug("SdncOscA1Client for ric: {}, a1Controller: {}", ricConfig.ricId(), controllerConfig); - } else { - throw new IllegalArgumentException("Not handeled protocolversion: " + protocolType); - } - - } - - @Override - public Mono> getPolicyTypeIdentities() { - if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) { - return Mono.just(Arrays.asList("")); - } else { - return post(GET_POLICY_RPC, getUriBuilder().createPolicyTypesUri(), Optional.empty()) // - .flatMapMany(SdncJsonHelper::parseJsonArrayOfString) // - .collectList(); - } - - } - - @Override - public Mono> getPolicyIdentities() { - return getPolicyIds() // - .collectList(); - } - - @Override - public Mono getPolicyTypeSchema(String policyTypeId) { - if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) { - return Mono.just("{}"); - } else { - A1UriBuilder uri = this.getUriBuilder(); - final String ricUrl = uri.createGetSchemaUri(policyTypeId); - return post(GET_POLICY_RPC, ricUrl, Optional.empty()) // - .flatMap(response -> extractCreateSchema(response, policyTypeId)); - } - } - - private Mono extractCreateSchema(String controllerResponse, String policyTypeId) { - if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) { - return OscA1Client.extractCreateSchema(controllerResponse, policyTypeId); - } else if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V2_0_0) { - return StdA1ClientVersion2.extractPolicySchema(controllerResponse, policyTypeId); - } else { - throw new NullPointerException("Not supported"); - } - } - - @Override - public Mono putPolicy(Policy policy) { - String ricUrl = - getUriBuilder().createPutPolicyUri(policy.type().id(), policy.id(), policy.statusNotificationUri()); - return post("putA1Policy", ricUrl, Optional.of(policy.json())); - } - - @Override - public Mono deletePolicy(Policy policy) { - return deletePolicyById(policy.type().id(), policy.id()); - } - - @Override - public Flux deleteAllPolicies() { - if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) { - return getPolicyIds() // - .flatMap(policyId -> deletePolicyById("", policyId), CONCURRENCY_RIC); // - } else { - A1UriBuilder uriBuilder = this.getUriBuilder(); - return getPolicyTypeIdentities() // - .flatMapMany(Flux::fromIterable) // - .flatMap(type -> deleteAllInstancesForType(uriBuilder, type), CONCURRENCY_RIC); - } - } - - private Flux getInstancesForType(A1UriBuilder uriBuilder, String type) { - return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(type), Optional.empty()) // - .flatMapMany(SdncJsonHelper::parseJsonArrayOfString); - } - - private Flux deleteAllInstancesForType(A1UriBuilder uriBuilder, String type) { - return getInstancesForType(uriBuilder, type) // - .flatMap(instance -> deletePolicyById(type, instance), CONCURRENCY_RIC); - } - - @Override - public Mono getProtocolVersion() { - return tryStdProtocolVersion2() // - .onErrorResume(t -> tryStdProtocolVersion1()) // - .onErrorResume(t -> tryOscProtocolVersion()); - } - - @Override - public Mono getPolicyStatus(Policy policy) { - String ricUrl = getUriBuilder().createGetPolicyStatusUri(policy.type().id(), policy.id()); - return post("getA1PolicyStatus", ricUrl, Optional.empty()); - - } - - private A1UriBuilder getUriBuilder() { - if (protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) { - return new StdA1ClientVersion1.UriBuilder(ricConfig); - } else if (protocolType == A1ProtocolType.SDNC_OSC_STD_V2_0_0) { - return new StdA1ClientVersion2.OranV2UriBuilder(ricConfig); - } else if (protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) { - return new OscA1Client.UriBuilder(ricConfig); - } - throw new NullPointerException(); - } - - private Mono tryOscProtocolVersion() { - OscA1Client.UriBuilder oscApiuriBuilder = new OscA1Client.UriBuilder(ricConfig); - return post(GET_POLICY_RPC, oscApiuriBuilder.createHealtcheckUri(), Optional.empty()) // - .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_OSC_V1)); - } - - private Mono tryStdProtocolVersion1() { - StdA1ClientVersion1.UriBuilder uriBuilder = new StdA1ClientVersion1.UriBuilder(ricConfig); - return post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(""), Optional.empty()) // - .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_STD_V1_1)); - } - - private Mono tryStdProtocolVersion2() { - StdA1ClientVersion2.OranV2UriBuilder uriBuilder = new StdA1ClientVersion2.OranV2UriBuilder(ricConfig); - return post(GET_POLICY_RPC, uriBuilder.createPolicyTypesUri(), Optional.empty()) // - .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC_STD_V2_0_0)); - } - - private Flux getPolicyIds() { - if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) { - StdA1ClientVersion1.UriBuilder uri = new StdA1ClientVersion1.UriBuilder(ricConfig); - final String ricUrl = uri.createGetPolicyIdsUri(""); - return post(GET_POLICY_RPC, ricUrl, Optional.empty()) // - .flatMapMany(SdncJsonHelper::parseJsonArrayOfString); - } else { - A1UriBuilder uri = this.getUriBuilder(); - return getPolicyTypeIdentities() // - .flatMapMany(Flux::fromIterable) - .flatMap(type -> post(GET_POLICY_RPC, uri.createGetPolicyIdsUri(type), Optional.empty())) // - .flatMap(SdncJsonHelper::parseJsonArrayOfString); - } - } - - private Mono deletePolicyById(String type, String policyId) { - String ricUrl = getUriBuilder().createDeleteUri(type, policyId); - return post("deleteA1Policy", ricUrl, Optional.empty()); - } - - private Mono post(String rpcName, String ricUrl, Optional body) { - AdapterRequest inputParams = ImmutableAdapterRequest.builder() // - .nearRtRicUrl(ricUrl) // - .body(body) // - .build(); - final String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - logger.debug("POST inputJsonString = {}", inputJsonString); - - return restClient - .postWithAuthHeader(controllerUrl(rpcName), inputJsonString, this.controllerConfig.userName(), - this.controllerConfig.password()) // - .flatMap(this::extractResponseBody); - } - - private Mono extractResponse(JSONObject responseOutput) { - AdapterOutput output = gson.fromJson(responseOutput.toString(), ImmutableAdapterOutput.class); - Optional optionalBody = output.body(); - String body = optionalBody.isPresent() ? optionalBody.get() : ""; - if (HttpStatus.valueOf(output.httpStatus()).is2xxSuccessful()) { - return Mono.just(body); - } else { - logger.debug("Error response: {} {}", output.httpStatus(), body); - byte[] responseBodyBytes = body.getBytes(StandardCharsets.UTF_8); - HttpStatus httpStatus = HttpStatus.valueOf(output.httpStatus()); - WebClientResponseException responseException = new WebClientResponseException(httpStatus.value(), - httpStatus.getReasonPhrase(), null, responseBodyBytes, StandardCharsets.UTF_8, null); - - return Mono.error(responseException); - } - } - - private Mono extractResponseBody(String responseStr) { - return SdncJsonHelper.getOutput(responseStr) // - .flatMap(this::extractResponse); - } - - private String controllerUrl(String rpcName) { - return "/A1-ADAPTER-API:" + rpcName; - } -} diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion1.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion1.java index a1c5ac7a..ba18afea 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion1.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion1.java @@ -151,7 +151,7 @@ public class StdA1ClientVersion1 implements A1Client { private Flux getPolicyIds() { return restClient.get(uri.createGetPolicyIdsUri("")) // - .flatMapMany(SdncJsonHelper::parseJsonArrayOfString); + .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString); } private Mono deletePolicyById(String policyId) { diff --git a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion2.java b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion2.java index cdf35954..471b3c4d 100644 --- a/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion2.java +++ b/a1-policy-management/src/main/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/StdA1ClientVersion2.java @@ -200,12 +200,12 @@ public class StdA1ClientVersion2 implements A1Client { private Flux getPolicyTypeIds() { return restClient.get(uriBuiler.createPolicyTypesUri()) // - .flatMapMany(SdncJsonHelper::parseJsonArrayOfString); + .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString); } private Flux getPolicyIdentitiesByType(String typeId) { return restClient.get(uriBuiler.createGetPolicyIdsUri(typeId)) // - .flatMapMany(SdncJsonHelper::parseJsonArrayOfString); + .flatMapMany(A1AdapterJsonHelper::parseJsonArrayOfString); } private Mono deletePolicyById(String typeId, String policyId) { diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactoryTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactoryTest.java index 89adf68a..3ca35430 100644 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactoryTest.java +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/A1ClientFactoryTest.java @@ -135,13 +135,12 @@ class A1ClientFactoryTest { void create_check_types_controllers() throws ServiceException { this.ric = new Ric(ricConfig("anythingButEmpty")); whenGetGetControllerConfigReturn(); - assertTrue(createClient(A1ProtocolType.SDNC_ONAP) instanceof SdncOnapA1Client); whenGetGetControllerConfigReturn(); - assertTrue(createClient(A1ProtocolType.SDNC_OSC_STD_V1_1) instanceof SdncOscA1Client); + assertTrue(createClient(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1) instanceof CcsdkA1AdapterClient); whenGetGetControllerConfigReturn(); - assertTrue(createClient(A1ProtocolType.SDNC_OSC_OSC_V1) instanceof SdncOscA1Client); + assertTrue(createClient(A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1) instanceof CcsdkA1AdapterClient); } private void whenGetProtocolVersionThrowException(A1Client... clientMocks) { diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/CcsdkA1AdapterClientTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/CcsdkA1AdapterClientTest.java new file mode 100644 index 00000000..87615f68 --- /dev/null +++ b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/CcsdkA1AdapterClientTest.java @@ -0,0 +1,414 @@ +/*- + * ========================LICENSE_START================================= + * ONAP : ccsdk oran + * ====================================================================== + * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.clients; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.stubbing.OngoingStubbing; +import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1Client.A1ProtocolType; +import org.onap.ccsdk.oran.a1policymanagementservice.clients.ImmutableAdapterOutput.Builder; +import org.onap.ccsdk.oran.a1policymanagementservice.clients.CcsdkA1AdapterClient.AdapterOutput; +import org.onap.ccsdk.oran.a1policymanagementservice.clients.CcsdkA1AdapterClient.AdapterRequest; +import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ControllerConfig; +import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableControllerConfig; +import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; +import org.springframework.http.HttpStatus; +import org.springframework.web.reactive.function.client.WebClientResponseException; + +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +@ExtendWith(MockitoExtension.class) +class CcsdkA1AdapterClientTest { + private static final String CONTROLLER_USERNAME = "username"; + private static final String CONTROLLER_PASSWORD = "password"; + private static final String RIC_1_URL = "RicUrl"; + private static final String GET_A1_POLICY_URL = "/A1-ADAPTER-API:getA1Policy"; + private static final String PUT_A1_URL = "/A1-ADAPTER-API:putA1Policy"; + private static final String DELETE_A1_URL = "/A1-ADAPTER-API:deleteA1Policy"; + private static final String GET_A1_POLICY_STATUS_URL = "/A1-ADAPTER-API:getA1PolicyStatus"; + private static final String POLICY_TYPE_1_ID = "type1"; + private static final String POLICY_1_ID = "policy1"; + private static final String POLICY_JSON_VALID = "{\"scope\":{\"ueId\":\"ue1\"}}"; + + CcsdkA1AdapterClient clientUnderTest; + + @Mock + AsyncRestClient asyncRestClientMock; + + private ControllerConfig controllerConfig() { + return ImmutableControllerConfig.builder() // + .name("name") // + .baseUrl("baseUrl") // + .password(CONTROLLER_PASSWORD) // + .userName(CONTROLLER_USERNAME) // + .build(); + } + + @Test + void createClientWithWrongProtocol_thenErrorIsThrown() { + assertThrows(IllegalArgumentException.class, () -> { + new CcsdkA1AdapterClient(A1ProtocolType.STD_V1_1, null, null, new AsyncRestClient("", null)); + }); + } + + @Test + void getPolicyTypeIdentities_STD_V1() { + clientUnderTest = new CcsdkA1AdapterClient(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1, // + A1ClientHelper.createRic(RIC_1_URL).getConfig(), // + controllerConfig(), asyncRestClientMock); + List policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block(); + assertEquals(1, policyTypeIds.size(), "should hardcoded to one"); + assertEquals("", policyTypeIds.get(0), "should hardcoded to empty"); + } + + private void testGetPolicyTypeIdentities(A1ProtocolType protocolType, String expUrl) { + clientUnderTest = new CcsdkA1AdapterClient(protocolType, // + A1ClientHelper.createRic(RIC_1_URL).getConfig(), // + controllerConfig(), asyncRestClientMock); + + String response = createOkResponseWithBody(Arrays.asList(POLICY_TYPE_1_ID)); + whenAsyncPostThenReturn(Mono.just(response)); + + List policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block(); + + assertEquals(1, policyTypeIds.size()); + assertEquals(POLICY_TYPE_1_ID, policyTypeIds.get(0)); + + ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() // + .nearRtRicUrl(expUrl) // + .build(); + String expInput = A1AdapterJsonHelper.createInputJsonString(expectedParams); + verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME, + CONTROLLER_PASSWORD); + } + + @Test + void getPolicyTypeIdentities_OSC() { + testGetPolicyTypeIdentities(A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1, RIC_1_URL + "/a1-p/policytypes"); + } + + @Test + void getPolicyTypeIdentities_STD_V2() { + testGetPolicyTypeIdentities(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0, RIC_1_URL + "/A1-P/v2/policytypes"); + } + + @Test + void getTypeSchema_STD_V1() { + + clientUnderTest = new CcsdkA1AdapterClient(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1, // + A1ClientHelper.createRic(RIC_1_URL).getConfig(), // + controllerConfig(), asyncRestClientMock); + + String policyType = clientUnderTest.getPolicyTypeSchema("").block(); + + assertEquals("{}", policyType); + } + + private void testGetTypeSchema(A1ProtocolType protocolType, String expUrl, String policyTypeId, + String getSchemaResponseFile) throws IOException { + clientUnderTest = new CcsdkA1AdapterClient(protocolType, // + A1ClientHelper.createRic(RIC_1_URL).getConfig(), // + controllerConfig(), asyncRestClientMock); + + String ricResponse = loadFile(getSchemaResponseFile); + JsonElement elem = gson().fromJson(ricResponse, JsonElement.class); + String responseFromController = createOkResponseWithBody(elem); + whenAsyncPostThenReturn(Mono.just(responseFromController)); + + String response = clientUnderTest.getPolicyTypeSchema(policyTypeId).block(); + + JsonElement respJson = gson().fromJson(response, JsonElement.class); + assertEquals(policyTypeId, respJson.getAsJsonObject().get("title").getAsString(), + "title should be updated to contain policyType ID"); + + ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() // + .nearRtRicUrl(expUrl) // + .build(); + String expInput = A1AdapterJsonHelper.createInputJsonString(expectedParams); + + verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME, + CONTROLLER_PASSWORD); + } + + @Test + void getTypeSchema_OSC() throws IOException { + String expUrl = RIC_1_URL + "/a1-p/policytypes/policyTypeId"; + testGetTypeSchema(A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1, expUrl, "policyTypeId", "test_osc_get_schema_response.json"); + } + + @Test + void getTypeSchema_STD_V2() throws IOException { + String expUrl = RIC_1_URL + "/A1-P/v2/policytypes/policyTypeId"; + testGetTypeSchema(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0, expUrl, "policyTypeId", + "test_oran_get_schema_response.json"); + } + + @Test + void parseJsonArrayOfString() { + // One integer and one string + String inputString = "[1, \"1\" ]"; + + List result = A1AdapterJsonHelper.parseJsonArrayOfString(inputString).collectList().block(); + assertEquals(2, result.size()); + assertEquals("1", result.get(0)); + assertEquals("1", result.get(1)); + } + + private void getPolicyIdentities(A1ProtocolType protocolType, String... expUrls) { + clientUnderTest = new CcsdkA1AdapterClient(protocolType, // + A1ClientHelper.createRic(RIC_1_URL).getConfig(), // + controllerConfig(), asyncRestClientMock); + String resp = createOkResponseWithBody(Arrays.asList("xxx")); + whenAsyncPostThenReturn(Mono.just(resp)); + + List returned = clientUnderTest.getPolicyIdentities().block(); + + assertEquals(1, returned.size()); + for (String expUrl : expUrls) { + ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() // + .nearRtRicUrl(expUrl) // + .build(); + String expInput = A1AdapterJsonHelper.createInputJsonString(expectedParams); + verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME, + CONTROLLER_PASSWORD); + } + } + + @Test + void getPolicyIdentities_STD_V1() { + String expUrl = RIC_1_URL + "/A1-P/v1/policies"; + getPolicyIdentities(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1, expUrl); + } + + @Test + void getPolicyIdentities_STD_V2() { + String expUrlPolicies = RIC_1_URL + "/A1-P/v2/policytypes"; + String expUrlInstances = RIC_1_URL + "/A1-P/v2/policytypes/xxx/policies"; + getPolicyIdentities(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0, expUrlPolicies, expUrlInstances); + } + + @Test + void getPolicyIdentities_OSC() { + String expUrlTypes = RIC_1_URL + "/a1-p/policytypes"; + String expUrlInstances = RIC_1_URL + "/a1-p/policytypes/xxx/policies"; + getPolicyIdentities(A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1, expUrlTypes, expUrlInstances); + } + + private void putPolicy(A1ProtocolType protocolType, String expUrl) { + clientUnderTest = new CcsdkA1AdapterClient(protocolType, // + A1ClientHelper.createRic(RIC_1_URL).getConfig(), // + controllerConfig(), asyncRestClientMock); + + whenPostReturnOkResponse(); + + String returned = clientUnderTest + .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID)) + .block(); + + assertEquals("OK", returned); + AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() // + .nearRtRicUrl(expUrl) // + .body(POLICY_JSON_VALID) // + .build(); + String expInput = A1AdapterJsonHelper.createInputJsonString(expectedInputParams); + + verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expInput, CONTROLLER_USERNAME, CONTROLLER_PASSWORD); + + } + + @Test + void putPolicy_OSC() { + String expUrl = RIC_1_URL + "/a1-p/policytypes/type1/policies/policy1"; + putPolicy(A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1, expUrl); + } + + @Test + void putPolicy_STD_V1() { + String expUrl = RIC_1_URL + "/A1-P/v1/policies/policy1"; + putPolicy(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1, expUrl); + } + + @Test + void putPolicy_STD_V2() { + String expUrl = + RIC_1_URL + "/A1-P/v2/policytypes/type1/policies/policy1?notificationDestination=https://test.com"; + putPolicy(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0, expUrl); + } + + @Test + void postRejected() { + clientUnderTest = new CcsdkA1AdapterClient(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1, // + A1ClientHelper.createRic(RIC_1_URL).getConfig(), // + controllerConfig(), asyncRestClientMock); + + final String policyJson = "{}"; + AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() // + .body("NOK") // + .httpStatus(HttpStatus.BAD_REQUEST.value()) // ERROR + .build(); + + String resp = A1AdapterJsonHelper.createOutputJsonString(adapterOutput); + whenAsyncPostThenReturn(Mono.just(resp)); + + Mono returnedMono = clientUnderTest + .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, policyJson, POLICY_TYPE_1_ID)); + StepVerifier.create(returnedMono) // + .expectSubscription() // + .expectErrorMatches(t -> t instanceof WebClientResponseException) // + .verify(); + + StepVerifier.create(returnedMono).expectErrorMatches(throwable -> { + return throwable instanceof WebClientResponseException; + }).verify(); + } + + private void deleteAllPolicies(A1ProtocolType protocolType, String expUrl) { + clientUnderTest = new CcsdkA1AdapterClient(protocolType, // + A1ClientHelper.createRic(RIC_1_URL).getConfig(), // + controllerConfig(), asyncRestClientMock); + String resp = createOkResponseWithBody(Arrays.asList("xxx")); + whenAsyncPostThenReturn(Mono.just(resp)); + + clientUnderTest.deleteAllPolicies().blockLast(); + + ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() // + .nearRtRicUrl(expUrl) // + .build(); + String expInput = A1AdapterJsonHelper.createInputJsonString(expectedParams); + verify(asyncRestClientMock).postWithAuthHeader(DELETE_A1_URL, expInput, CONTROLLER_USERNAME, + CONTROLLER_PASSWORD); + } + + @Test + void deleteAllPolicies_STD_V2() { + String expUrl1 = RIC_1_URL + "/A1-P/v2/policytypes/xxx/policies/xxx"; + deleteAllPolicies(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0, expUrl1); + } + + @Test + void deleteAllPolicies_STD_V1() { + String expUrl1 = RIC_1_URL + "/A1-P/v1/policies/xxx"; + deleteAllPolicies(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1, expUrl1); + } + + @Test + void deleteAllPolicies_OSC() { + String expUrl1 = RIC_1_URL + "/a1-p/policytypes/xxx/policies/xxx"; + deleteAllPolicies(A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1, expUrl1); + } + + @Test + void getVersion_OSC() { + clientUnderTest = new CcsdkA1AdapterClient(A1ProtocolType.CCSDK_A1_ADAPTER_OSC_V1, // Version irrelevant here + A1ClientHelper.createRic(RIC_1_URL).getConfig(), // + controllerConfig(), asyncRestClientMock); + + whenAsyncPostThenReturn(Mono.error(new Exception("Error"))).thenReturn(Mono.just(createOkResponseString(true))); + + A1ProtocolType returnedVersion = clientUnderTest.getProtocolVersion().block(); + + assertEquals(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V1_1, returnedVersion); + } + + @Test + void testGetStatus() { + clientUnderTest = new CcsdkA1AdapterClient(A1ProtocolType.CCSDK_A1_ADAPTER_STD_V2_0_0, // + A1ClientHelper.createRic(RIC_1_URL).getConfig(), // + controllerConfig(), asyncRestClientMock); + whenPostReturnOkResponse(); + + Policy policy = A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID); + + String response = clientUnderTest.getPolicyStatus(policy).block(); + assertEquals("OK", response); + + String expUrl = RIC_1_URL + "/A1-P/v2/policytypes/type1/policies/policy1/status"; + ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() // + .nearRtRicUrl(expUrl) // + .build(); + String expInput = A1AdapterJsonHelper.createInputJsonString(expectedParams); + verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_STATUS_URL, expInput, CONTROLLER_USERNAME, + CONTROLLER_PASSWORD); + + } + + private Gson gson() { + return CcsdkA1AdapterClient.gson; + } + + private String loadFile(String fileName) throws IOException { + ClassLoader loader = Thread.currentThread().getContextClassLoader(); + URL url = loader.getResource(fileName); + File file = new File(url.getFile()); + return new String(Files.readAllBytes(file.toPath())); + } + + private void whenPostReturnOkResponse() { + whenAsyncPostThenReturn(Mono.just(createOkResponseString(true))); + } + + void whenPostReturnOkResponseNoBody() { + whenAsyncPostThenReturn(Mono.just(createOkResponseString(false))); + } + + private String createOkResponseWithBody(Object body) { + AdapterOutput output = ImmutableAdapterOutput.builder() // + .body(gson().toJson(body)) // + .httpStatus(HttpStatus.OK.value()) // + .build(); + return A1AdapterJsonHelper.createOutputJsonString(output); + } + + private String createOkResponseString(boolean withBody) { + Builder responseBuilder = ImmutableAdapterOutput.builder().httpStatus(HttpStatus.OK.value()); + if (withBody) { + responseBuilder.body(HttpStatus.OK.name()); + } else { + responseBuilder.body(Optional.empty()); + } + return A1AdapterJsonHelper.createOutputJsonString(responseBuilder.build()); + } + + private OngoingStubbing> whenAsyncPostThenReturn(Mono response) { + return when(asyncRestClientMock.postWithAuthHeader(anyString(), anyString(), anyString(), anyString())) + .thenReturn(response); + } +} diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1ClientTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1ClientTest.java deleted file mode 100644 index c2118c12..00000000 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOnapA1ClientTest.java +++ /dev/null @@ -1,271 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.clients; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.json.JSONException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.stubbing.OngoingStubbing; -import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ControllerConfig; -import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableControllerConfig; - -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -@ExtendWith(MockitoExtension.class) -class SdncOnapA1ClientTest { - private static final String CONTROLLER_USERNAME = "username"; - private static final String CONTROLLER_PASSWORD = "password"; - private static final String RIC_1_URL = "RicUrl"; - private static final String POLICYTYPES_IDENTITIES_URL = "/A1-ADAPTER-API:getPolicyTypes"; - private static final String POLICIES_IDENTITIES_URL = "/A1-ADAPTER-API:getPolicyInstances"; - private static final String POLICYTYPES_URL = "/A1-ADAPTER-API:getPolicyType"; - private static final String PUT_POLICY_URL = "/A1-ADAPTER-API:createPolicyInstance"; - private static final String DELETE_POLICY_URL = "/A1-ADAPTER-API:deletePolicyInstance"; - - private static final String POLICY_TYPE_1_ID = "type1"; - private static final String POLICY_TYPE_2_ID = "type2"; - private static final String POLICY_TYPE_SCHEMA_VALID = "{\"type\":\"type1\"}"; - private static final String POLICY_TYPE_SCHEMA_INVALID = "\"type\":\"type1\"}"; - private static final String POLICY_1_ID = "policy1"; - private static final String POLICY_2_ID = "policy2"; - private static final String POLICY_JSON_VALID = "{\"scope\":{\"ueId\":\"ue1\"}}"; - - SdncOnapA1Client clientUnderTest; - - AsyncRestClient asyncRestClientMock; - - @BeforeEach - void init() { - asyncRestClientMock = mock(AsyncRestClient.class); - ControllerConfig controllerCfg = ImmutableControllerConfig.builder() // - .name("name") // - .baseUrl("baseUrl") // - .password(CONTROLLER_PASSWORD) // - .userName(CONTROLLER_USERNAME) // - .build(); - - clientUnderTest = new SdncOnapA1Client(A1ClientHelper.createRic(RIC_1_URL).getConfig(), controllerCfg, - asyncRestClientMock); - } - - @Test - void testGetPolicyTypeIdentities() { - SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .build(); - String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - - List policyTypeIds = Arrays.asList(POLICY_TYPE_1_ID, POLICY_TYPE_2_ID); - Mono policyTypeIdsResp = - A1ClientHelper.createOutputJsonResponse("policy-type-id-list", policyTypeIds.toString()); - whenAsyncPostThenReturn(policyTypeIdsResp); - - Mono> returnedMono = clientUnderTest.getPolicyTypeIdentities(); - verify(asyncRestClientMock).postWithAuthHeader(POLICYTYPES_IDENTITIES_URL, inputJsonString, CONTROLLER_USERNAME, - CONTROLLER_PASSWORD); - StepVerifier.create(returnedMono).expectNext(policyTypeIds).expectComplete().verify(); - } - - @Test - void testGetPolicyIdentities() { - SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .build(); - String inputJsonStringGetTypeIds = SdncJsonHelper.createInputJsonString(inputParams); - inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .policyTypeId(POLICY_TYPE_1_ID) // - .build(); - String inputJsonStringGetPolicyIdsType1 = SdncJsonHelper.createInputJsonString(inputParams); - inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .policyTypeId(POLICY_TYPE_2_ID) // - .build(); - String inputJsonStringGetPolicyIdsType2 = SdncJsonHelper.createInputJsonString(inputParams); - - List policyTypeIds = Arrays.asList(POLICY_TYPE_1_ID, POLICY_TYPE_2_ID); - Mono policyTypeIdsResp = - A1ClientHelper.createOutputJsonResponse("policy-type-id-list", policyTypeIds.toString()); - List policyIdsType1 = Arrays.asList(POLICY_1_ID); - Mono policyIdsType1Resp = - A1ClientHelper.createOutputJsonResponse("policy-instance-id-list", policyIdsType1.toString()); - List policyIdsType2 = Arrays.asList(POLICY_2_ID); - Mono policyIdsType2Resp = - A1ClientHelper.createOutputJsonResponse("policy-instance-id-list", policyIdsType2.toString()); - whenAsyncPostThenReturn(policyTypeIdsResp).thenReturn(policyIdsType1Resp).thenReturn(policyIdsType2Resp); - - Mono> returnedMono = clientUnderTest.getPolicyIdentities(); - StepVerifier.create(returnedMono).expectNext(Arrays.asList(POLICY_1_ID, POLICY_2_ID)).expectComplete().verify(); - verify(asyncRestClientMock).postWithAuthHeader(POLICYTYPES_IDENTITIES_URL, inputJsonStringGetTypeIds, - CONTROLLER_USERNAME, CONTROLLER_PASSWORD); - verify(asyncRestClientMock).postWithAuthHeader(POLICIES_IDENTITIES_URL, inputJsonStringGetPolicyIdsType1, - CONTROLLER_USERNAME, CONTROLLER_PASSWORD); - verify(asyncRestClientMock).postWithAuthHeader(POLICIES_IDENTITIES_URL, inputJsonStringGetPolicyIdsType2, - CONTROLLER_USERNAME, CONTROLLER_PASSWORD); - } - - @Test - void testGetValidPolicyType() { - SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .policyTypeId(POLICY_TYPE_1_ID) // - .build(); - String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - - String policyType = "{\"policySchema\": " + POLICY_TYPE_SCHEMA_VALID + ", \"statusSchema\": {} }"; - Mono policyTypeResp = A1ClientHelper.createOutputJsonResponse("policy-type", policyType); - whenAsyncPostThenReturn(policyTypeResp); - - Mono returnedMono = clientUnderTest.getPolicyTypeSchema(POLICY_TYPE_1_ID); - verify(asyncRestClientMock).postWithAuthHeader(POLICYTYPES_URL, inputJsonString, CONTROLLER_USERNAME, - CONTROLLER_PASSWORD); - StepVerifier.create(returnedMono).expectNext(POLICY_TYPE_SCHEMA_VALID).expectComplete().verify(); - } - - @Test - void testGetInvalidPolicyType() { - SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .policyTypeId(POLICY_TYPE_1_ID) // - .build(); - String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - - String policyType = "{\"policySchema\": " + POLICY_TYPE_SCHEMA_INVALID + ", \"statusSchema\": {} }"; - Mono policyTypeResp = A1ClientHelper.createOutputJsonResponse("policy-type", policyType); - whenAsyncPostThenReturn(policyTypeResp); - - Mono returnedMono = clientUnderTest.getPolicyTypeSchema(POLICY_TYPE_1_ID); - verify(asyncRestClientMock).postWithAuthHeader(POLICYTYPES_URL, inputJsonString, CONTROLLER_USERNAME, - CONTROLLER_PASSWORD); - StepVerifier.create(returnedMono).expectErrorMatches(throwable -> throwable instanceof JSONException).verify(); - } - - @Test - void testPutPolicy() { - SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .policyTypeId(POLICY_TYPE_1_ID) // - .policyInstanceId(POLICY_1_ID) // - .policyInstance(POLICY_JSON_VALID) // - .properties(new ArrayList()) // - .build(); - String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - - whenAsyncPostThenReturn(Mono.empty()); - - Mono returnedMono = clientUnderTest - .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID)); - verify(asyncRestClientMock).postWithAuthHeader(PUT_POLICY_URL, inputJsonString, CONTROLLER_USERNAME, - CONTROLLER_PASSWORD); - StepVerifier.create(returnedMono).expectComplete().verify(); - } - - @Test - void testDeletePolicy() { - SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .policyTypeId(POLICY_TYPE_1_ID) // - .policyInstanceId(POLICY_1_ID) // - .build(); - String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams); - - whenAsyncPostThenReturn(Mono.empty()); - - Mono returnedMono = clientUnderTest - .deletePolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID)); - verify(asyncRestClientMock).postWithAuthHeader(DELETE_POLICY_URL, inputJsonString, CONTROLLER_USERNAME, - CONTROLLER_PASSWORD); - StepVerifier.create(returnedMono).expectComplete().verify(); - } - - @Test - void testDeleteAllPolicies() { - SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .build(); - String inputJsonStringGetTypeIds = SdncJsonHelper.createInputJsonString(inputParams); - inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .policyTypeId(POLICY_TYPE_1_ID) // - .build(); - String inputJsonStringGetPolicyIdsType1 = SdncJsonHelper.createInputJsonString(inputParams); - inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .policyTypeId(POLICY_TYPE_2_ID) // - .build(); - String inputJsonStringGetPolicyIdsType2 = SdncJsonHelper.createInputJsonString(inputParams); - inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .policyTypeId(POLICY_TYPE_1_ID) // - .policyInstanceId(POLICY_1_ID) // - .build(); - String inputJsonStringDeletePolicy1 = SdncJsonHelper.createInputJsonString(inputParams); - inputParams = ImmutableSdncOnapAdapterInput.builder() // - .nearRtRicId(RIC_1_URL) // - .policyTypeId(POLICY_TYPE_2_ID) // - .policyInstanceId(POLICY_2_ID) // - .build(); - String inputJsonStringDeletePolicy2 = SdncJsonHelper.createInputJsonString(inputParams); - - List policyTypeIds = Arrays.asList(POLICY_TYPE_1_ID, POLICY_TYPE_2_ID); - Mono policyTypeIdsResp = - A1ClientHelper.createOutputJsonResponse("policy-type-id-list", policyTypeIds.toString()); - List policyIdsType1 = Arrays.asList(POLICY_1_ID); - Mono policyIdsType1Resp = - A1ClientHelper.createOutputJsonResponse("policy-instance-id-list", policyIdsType1.toString()); - List policyIdsType2 = Arrays.asList(POLICY_2_ID); - Mono policyIdsType2Resp = - A1ClientHelper.createOutputJsonResponse("policy-instance-id-list", policyIdsType2.toString()); - whenAsyncPostThenReturn(policyTypeIdsResp).thenReturn(policyIdsType1Resp).thenReturn(Mono.empty()) - .thenReturn(policyIdsType2Resp).thenReturn(Mono.empty()); - - Flux returnedFlux = clientUnderTest.deleteAllPolicies(); - StepVerifier.create(returnedFlux).expectComplete().verify(); - verify(asyncRestClientMock).postWithAuthHeader(POLICYTYPES_IDENTITIES_URL, inputJsonStringGetTypeIds, - CONTROLLER_USERNAME, CONTROLLER_PASSWORD); - verify(asyncRestClientMock).postWithAuthHeader(POLICIES_IDENTITIES_URL, inputJsonStringGetPolicyIdsType1, - CONTROLLER_USERNAME, CONTROLLER_PASSWORD); - verify(asyncRestClientMock).postWithAuthHeader(DELETE_POLICY_URL, inputJsonStringDeletePolicy1, - CONTROLLER_USERNAME, CONTROLLER_PASSWORD); - verify(asyncRestClientMock).postWithAuthHeader(POLICIES_IDENTITIES_URL, inputJsonStringGetPolicyIdsType2, - CONTROLLER_USERNAME, CONTROLLER_PASSWORD); - verify(asyncRestClientMock).postWithAuthHeader(DELETE_POLICY_URL, inputJsonStringDeletePolicy2, - CONTROLLER_USERNAME, CONTROLLER_PASSWORD); - } - - private OngoingStubbing> whenAsyncPostThenReturn(Mono response) { - return when(asyncRestClientMock.postWithAuthHeader(anyString(), anyString(), anyString(), anyString())) - .thenReturn(response); - } -} diff --git a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1ClientTest.java b/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1ClientTest.java deleted file mode 100644 index 4eca44d4..00000000 --- a/a1-policy-management/src/test/java/org/onap/ccsdk/oran/a1policymanagementservice/clients/SdncOscA1ClientTest.java +++ /dev/null @@ -1,414 +0,0 @@ -/*- - * ========================LICENSE_START================================= - * ONAP : ccsdk oran - * ====================================================================== - * Copyright (C) 2020 Nordix Foundation. 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.ccsdk.oran.a1policymanagementservice.clients; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.nio.file.Files; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.stubbing.OngoingStubbing; -import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1Client.A1ProtocolType; -import org.onap.ccsdk.oran.a1policymanagementservice.clients.ImmutableAdapterOutput.Builder; -import org.onap.ccsdk.oran.a1policymanagementservice.clients.SdncOscA1Client.AdapterOutput; -import org.onap.ccsdk.oran.a1policymanagementservice.clients.SdncOscA1Client.AdapterRequest; -import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ControllerConfig; -import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableControllerConfig; -import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy; -import org.springframework.http.HttpStatus; -import org.springframework.web.reactive.function.client.WebClientResponseException; - -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -@ExtendWith(MockitoExtension.class) -class SdncOscA1ClientTest { - private static final String CONTROLLER_USERNAME = "username"; - private static final String CONTROLLER_PASSWORD = "password"; - private static final String RIC_1_URL = "RicUrl"; - private static final String GET_A1_POLICY_URL = "/A1-ADAPTER-API:getA1Policy"; - private static final String PUT_A1_URL = "/A1-ADAPTER-API:putA1Policy"; - private static final String DELETE_A1_URL = "/A1-ADAPTER-API:deleteA1Policy"; - private static final String GET_A1_POLICY_STATUS_URL = "/A1-ADAPTER-API:getA1PolicyStatus"; - private static final String POLICY_TYPE_1_ID = "type1"; - private static final String POLICY_1_ID = "policy1"; - private static final String POLICY_JSON_VALID = "{\"scope\":{\"ueId\":\"ue1\"}}"; - - SdncOscA1Client clientUnderTest; - - @Mock - AsyncRestClient asyncRestClientMock; - - private ControllerConfig controllerConfig() { - return ImmutableControllerConfig.builder() // - .name("name") // - .baseUrl("baseUrl") // - .password(CONTROLLER_PASSWORD) // - .userName(CONTROLLER_USERNAME) // - .build(); - } - - @Test - void createClientWithWrongProtocol_thenErrorIsThrown() { - assertThrows(IllegalArgumentException.class, () -> { - new SdncOscA1Client(A1ProtocolType.STD_V1_1, null, null, new AsyncRestClient("", null)); - }); - } - - @Test - void getPolicyTypeIdentities_STD_V1() { - clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_STD_V1_1, // - A1ClientHelper.createRic(RIC_1_URL).getConfig(), // - controllerConfig(), asyncRestClientMock); - List policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block(); - assertEquals(1, policyTypeIds.size(), "should hardcoded to one"); - assertEquals("", policyTypeIds.get(0), "should hardcoded to empty"); - } - - private void testGetPolicyTypeIdentities(A1ProtocolType protocolType, String expUrl) { - clientUnderTest = new SdncOscA1Client(protocolType, // - A1ClientHelper.createRic(RIC_1_URL).getConfig(), // - controllerConfig(), asyncRestClientMock); - - String response = createOkResponseWithBody(Arrays.asList(POLICY_TYPE_1_ID)); - whenAsyncPostThenReturn(Mono.just(response)); - - List policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block(); - - assertEquals(1, policyTypeIds.size()); - assertEquals(POLICY_TYPE_1_ID, policyTypeIds.get(0)); - - ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() // - .nearRtRicUrl(expUrl) // - .build(); - String expInput = SdncJsonHelper.createInputJsonString(expectedParams); - verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME, - CONTROLLER_PASSWORD); - } - - @Test - void getPolicyTypeIdentities_OSC() { - testGetPolicyTypeIdentities(A1ProtocolType.SDNC_OSC_OSC_V1, RIC_1_URL + "/a1-p/policytypes"); - } - - @Test - void getPolicyTypeIdentities_STD_V2() { - testGetPolicyTypeIdentities(A1ProtocolType.SDNC_OSC_STD_V2_0_0, RIC_1_URL + "/A1-P/v2/policytypes"); - } - - @Test - void getTypeSchema_STD_V1() { - - clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_STD_V1_1, // - A1ClientHelper.createRic(RIC_1_URL).getConfig(), // - controllerConfig(), asyncRestClientMock); - - String policyType = clientUnderTest.getPolicyTypeSchema("").block(); - - assertEquals("{}", policyType); - } - - private void testGetTypeSchema(A1ProtocolType protocolType, String expUrl, String policyTypeId, - String getSchemaResponseFile) throws IOException { - clientUnderTest = new SdncOscA1Client(protocolType, // - A1ClientHelper.createRic(RIC_1_URL).getConfig(), // - controllerConfig(), asyncRestClientMock); - - String ricResponse = loadFile(getSchemaResponseFile); - JsonElement elem = gson().fromJson(ricResponse, JsonElement.class); - String responseFromController = createOkResponseWithBody(elem); - whenAsyncPostThenReturn(Mono.just(responseFromController)); - - String response = clientUnderTest.getPolicyTypeSchema(policyTypeId).block(); - - JsonElement respJson = gson().fromJson(response, JsonElement.class); - assertEquals(policyTypeId, respJson.getAsJsonObject().get("title").getAsString(), - "title should be updated to contain policyType ID"); - - ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() // - .nearRtRicUrl(expUrl) // - .build(); - String expInput = SdncJsonHelper.createInputJsonString(expectedParams); - - verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME, - CONTROLLER_PASSWORD); - } - - @Test - void getTypeSchema_OSC() throws IOException { - String expUrl = RIC_1_URL + "/a1-p/policytypes/policyTypeId"; - testGetTypeSchema(A1ProtocolType.SDNC_OSC_OSC_V1, expUrl, "policyTypeId", "test_osc_get_schema_response.json"); - } - - @Test - void getTypeSchema_STD_V2() throws IOException { - String expUrl = RIC_1_URL + "/A1-P/v2/policytypes/policyTypeId"; - testGetTypeSchema(A1ProtocolType.SDNC_OSC_STD_V2_0_0, expUrl, "policyTypeId", - "test_oran_get_schema_response.json"); - } - - @Test - void parseJsonArrayOfString() { - // One integer and one string - String inputString = "[1, \"1\" ]"; - - List result = SdncJsonHelper.parseJsonArrayOfString(inputString).collectList().block(); - assertEquals(2, result.size()); - assertEquals("1", result.get(0)); - assertEquals("1", result.get(1)); - } - - private void getPolicyIdentities(A1ProtocolType protocolType, String... expUrls) { - clientUnderTest = new SdncOscA1Client(protocolType, // - A1ClientHelper.createRic(RIC_1_URL).getConfig(), // - controllerConfig(), asyncRestClientMock); - String resp = createOkResponseWithBody(Arrays.asList("xxx")); - whenAsyncPostThenReturn(Mono.just(resp)); - - List returned = clientUnderTest.getPolicyIdentities().block(); - - assertEquals(1, returned.size()); - for (String expUrl : expUrls) { - ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() // - .nearRtRicUrl(expUrl) // - .build(); - String expInput = SdncJsonHelper.createInputJsonString(expectedParams); - verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME, - CONTROLLER_PASSWORD); - } - } - - @Test - void getPolicyIdentities_STD_V1() { - String expUrl = RIC_1_URL + "/A1-P/v1/policies"; - getPolicyIdentities(A1ProtocolType.SDNC_OSC_STD_V1_1, expUrl); - } - - @Test - void getPolicyIdentities_STD_V2() { - String expUrlPolicies = RIC_1_URL + "/A1-P/v2/policytypes"; - String expUrlInstances = RIC_1_URL + "/A1-P/v2/policytypes/xxx/policies"; - getPolicyIdentities(A1ProtocolType.SDNC_OSC_STD_V2_0_0, expUrlPolicies, expUrlInstances); - } - - @Test - void getPolicyIdentities_OSC() { - String expUrlTypes = RIC_1_URL + "/a1-p/policytypes"; - String expUrlInstances = RIC_1_URL + "/a1-p/policytypes/xxx/policies"; - getPolicyIdentities(A1ProtocolType.SDNC_OSC_OSC_V1, expUrlTypes, expUrlInstances); - } - - private void putPolicy(A1ProtocolType protocolType, String expUrl) { - clientUnderTest = new SdncOscA1Client(protocolType, // - A1ClientHelper.createRic(RIC_1_URL).getConfig(), // - controllerConfig(), asyncRestClientMock); - - whenPostReturnOkResponse(); - - String returned = clientUnderTest - .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID)) - .block(); - - assertEquals("OK", returned); - AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() // - .nearRtRicUrl(expUrl) // - .body(POLICY_JSON_VALID) // - .build(); - String expInput = SdncJsonHelper.createInputJsonString(expectedInputParams); - - verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expInput, CONTROLLER_USERNAME, CONTROLLER_PASSWORD); - - } - - @Test - void putPolicy_OSC() { - String expUrl = RIC_1_URL + "/a1-p/policytypes/type1/policies/policy1"; - putPolicy(A1ProtocolType.SDNC_OSC_OSC_V1, expUrl); - } - - @Test - void putPolicy_STD_V1() { - String expUrl = RIC_1_URL + "/A1-P/v1/policies/policy1"; - putPolicy(A1ProtocolType.SDNC_OSC_STD_V1_1, expUrl); - } - - @Test - void putPolicy_STD_V2() { - String expUrl = - RIC_1_URL + "/A1-P/v2/policytypes/type1/policies/policy1?notificationDestination=https://test.com"; - putPolicy(A1ProtocolType.SDNC_OSC_STD_V2_0_0, expUrl); - } - - @Test - void postRejected() { - clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_STD_V1_1, // - A1ClientHelper.createRic(RIC_1_URL).getConfig(), // - controllerConfig(), asyncRestClientMock); - - final String policyJson = "{}"; - AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() // - .body("NOK") // - .httpStatus(HttpStatus.BAD_REQUEST.value()) // ERROR - .build(); - - String resp = SdncJsonHelper.createOutputJsonString(adapterOutput); - whenAsyncPostThenReturn(Mono.just(resp)); - - Mono returnedMono = clientUnderTest - .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, policyJson, POLICY_TYPE_1_ID)); - StepVerifier.create(returnedMono) // - .expectSubscription() // - .expectErrorMatches(t -> t instanceof WebClientResponseException) // - .verify(); - - StepVerifier.create(returnedMono).expectErrorMatches(throwable -> { - return throwable instanceof WebClientResponseException; - }).verify(); - } - - private void deleteAllPolicies(A1ProtocolType protocolType, String expUrl) { - clientUnderTest = new SdncOscA1Client(protocolType, // - A1ClientHelper.createRic(RIC_1_URL).getConfig(), // - controllerConfig(), asyncRestClientMock); - String resp = createOkResponseWithBody(Arrays.asList("xxx")); - whenAsyncPostThenReturn(Mono.just(resp)); - - clientUnderTest.deleteAllPolicies().blockLast(); - - ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() // - .nearRtRicUrl(expUrl) // - .build(); - String expInput = SdncJsonHelper.createInputJsonString(expectedParams); - verify(asyncRestClientMock).postWithAuthHeader(DELETE_A1_URL, expInput, CONTROLLER_USERNAME, - CONTROLLER_PASSWORD); - } - - @Test - void deleteAllPolicies_STD_V2() { - String expUrl1 = RIC_1_URL + "/A1-P/v2/policytypes/xxx/policies/xxx"; - deleteAllPolicies(A1ProtocolType.SDNC_OSC_STD_V2_0_0, expUrl1); - } - - @Test - void deleteAllPolicies_STD_V1() { - String expUrl1 = RIC_1_URL + "/A1-P/v1/policies/xxx"; - deleteAllPolicies(A1ProtocolType.SDNC_OSC_STD_V1_1, expUrl1); - } - - @Test - void deleteAllPolicies_OSC() { - String expUrl1 = RIC_1_URL + "/a1-p/policytypes/xxx/policies/xxx"; - deleteAllPolicies(A1ProtocolType.SDNC_OSC_OSC_V1, expUrl1); - } - - @Test - void getVersion_OSC() { - clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, // Version irrelevant here - A1ClientHelper.createRic(RIC_1_URL).getConfig(), // - controllerConfig(), asyncRestClientMock); - - whenAsyncPostThenReturn(Mono.error(new Exception("Error"))).thenReturn(Mono.just(createOkResponseString(true))); - - A1ProtocolType returnedVersion = clientUnderTest.getProtocolVersion().block(); - - assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion); - } - - @Test - void testGetStatus() { - clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_STD_V2_0_0, // - A1ClientHelper.createRic(RIC_1_URL).getConfig(), // - controllerConfig(), asyncRestClientMock); - whenPostReturnOkResponse(); - - Policy policy = A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID); - - String response = clientUnderTest.getPolicyStatus(policy).block(); - assertEquals("OK", response); - - String expUrl = RIC_1_URL + "/A1-P/v2/policytypes/type1/policies/policy1/status"; - ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() // - .nearRtRicUrl(expUrl) // - .build(); - String expInput = SdncJsonHelper.createInputJsonString(expectedParams); - verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_STATUS_URL, expInput, CONTROLLER_USERNAME, - CONTROLLER_PASSWORD); - - } - - private Gson gson() { - return SdncOscA1Client.gson; - } - - private String loadFile(String fileName) throws IOException { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - URL url = loader.getResource(fileName); - File file = new File(url.getFile()); - return new String(Files.readAllBytes(file.toPath())); - } - - private void whenPostReturnOkResponse() { - whenAsyncPostThenReturn(Mono.just(createOkResponseString(true))); - } - - void whenPostReturnOkResponseNoBody() { - whenAsyncPostThenReturn(Mono.just(createOkResponseString(false))); - } - - private String createOkResponseWithBody(Object body) { - AdapterOutput output = ImmutableAdapterOutput.builder() // - .body(gson().toJson(body)) // - .httpStatus(HttpStatus.OK.value()) // - .build(); - return SdncJsonHelper.createOutputJsonString(output); - } - - private String createOkResponseString(boolean withBody) { - Builder responseBuilder = ImmutableAdapterOutput.builder().httpStatus(HttpStatus.OK.value()); - if (withBody) { - responseBuilder.body(HttpStatus.OK.name()); - } else { - responseBuilder.body(Optional.empty()); - } - return SdncJsonHelper.createOutputJsonString(responseBuilder.build()); - } - - private OngoingStubbing> whenAsyncPostThenReturn(Mono response) { - return when(asyncRestClientMock.postWithAuthHeader(anyString(), anyString(), anyString(), anyString())) - .thenReturn(response); - } -} -- cgit 1.2.3-korg