+++ /dev/null
----
-distribution_type: container
-container_release_tag: 1.0.1
-container_pull_registry: nexus3.o-ran-sc.org:10004
-container_push_registry: nexus3.o-ran-sc.org:10002
-project: nonrtric
-ref: 08691d2192981c302a5528669fdb71e48cb3dcbc
-containers:
- - name: nonrtric-dashboard
- version: 1.0.1
.settings
target
.checkstyle
-policy-agent.iml
\ No newline at end of file
+policy-agent.iml
description: Ric Repository Controller
- name: Service registry and supervision
description: Service Controller
- - name: operation-handler
- description: Operation Handler
- - name: web-mvc-links-handler
- description: Web Mvc Links Handler
paths:
- /actuator:
- get:
- tags:
- - web-mvc-links-handler
- summary: links
- operationId: linksUsingGET
- produces:
- - application/vnd.spring-boot.actuator.v3+json
- - application/json
- - application/vnd.spring-boot.actuator.v2+json
- responses:
- '200':
- description: OK
- schema:
- type: object
- additionalProperties:
- type: object
- additionalProperties:
- $ref: '#/definitions/Link'
- '401':
- description: Unauthorized
- '403':
- description: Forbidden
- '404':
- description: Not Found
- deprecated: false
- /actuator/health:
- get:
- tags:
- - operation-handler
- summary: handle
- operationId: handleUsingGET_1
- produces:
- - application/vnd.spring-boot.actuator.v3+json
- - application/json
- - application/vnd.spring-boot.actuator.v2+json
- parameters:
- - in: body
- name: body
- description: body
- required: false
- schema:
- type: object
- additionalProperties:
- type: string
- responses:
- '200':
- description: OK
- schema:
- type: object
- '401':
- description: Unauthorized
- '403':
- description: Forbidden
- '404':
- description: Not Found
- deprecated: false
- /actuator/health/**:
- get:
- tags:
- - operation-handler
- summary: handle
- operationId: handleUsingGET
- produces:
- - application/vnd.spring-boot.actuator.v3+json
- - application/json
- - application/vnd.spring-boot.actuator.v2+json
- parameters:
- - in: body
- name: body
- description: body
- required: false
- schema:
- type: object
- additionalProperties:
- type: string
- responses:
- '200':
- description: OK
- schema:
- type: object
- '401':
- description: Unauthorized
- '403':
- description: Forbidden
- '404':
- description: Not Found
- deprecated: false
- /actuator/info:
- get:
- tags:
- - operation-handler
- summary: handle
- operationId: handleUsingGET_2
- produces:
- - application/vnd.spring-boot.actuator.v3+json
- - application/json
- - application/vnd.spring-boot.actuator.v2+json
- parameters:
- - in: body
- name: body
- description: body
- required: false
- schema:
- type: object
- additionalProperties:
- type: string
- responses:
- '200':
- description: OK
- schema:
- type: object
- '401':
- description: Unauthorized
- '403':
- description: Forbidden
- '404':
- description: Not Found
- deprecated: false
- /actuator/logfile:
- get:
- tags:
- - operation-handler
- summary: handle
- operationId: handleUsingGET_3
- produces:
- - text/plain;charset=UTF-8
- parameters:
- - in: body
- name: body
- description: body
- required: false
- schema:
- type: object
- additionalProperties:
- type: string
- responses:
- '200':
- description: OK
- schema:
- type: object
- '401':
- description: Unauthorized
- '403':
- description: Forbidden
- '404':
- description: Not Found
- deprecated: false
- /actuator/loggers:
- get:
- tags:
- - operation-handler
- summary: handle
- operationId: handleUsingGET_5
- produces:
- - application/vnd.spring-boot.actuator.v3+json
- - application/json
- - application/vnd.spring-boot.actuator.v2+json
- parameters:
- - in: body
- name: body
- description: body
- required: false
- schema:
- type: object
- additionalProperties:
- type: string
- responses:
- '200':
- description: OK
- schema:
- type: object
- '401':
- description: Unauthorized
- '403':
- description: Forbidden
- '404':
- description: Not Found
- deprecated: false
- '/actuator/loggers/{name}':
- get:
- tags:
- - operation-handler
- summary: handle
- operationId: handleUsingGET_4
- produces:
- - application/vnd.spring-boot.actuator.v3+json
- - application/json
- - application/vnd.spring-boot.actuator.v2+json
- parameters:
- - in: body
- name: body
- description: body
- required: false
- schema:
- type: object
- additionalProperties:
- type: string
- responses:
- '200':
- description: OK
- schema:
- type: object
- '401':
- description: Unauthorized
- '403':
- description: Forbidden
- '404':
- description: Not Found
- deprecated: false
- post:
- tags:
- - operation-handler
- summary: handle
- operationId: handleUsingPOST
- consumes:
- - application/vnd.spring-boot.actuator.v3+json
- - application/json
- - application/vnd.spring-boot.actuator.v2+json
- produces:
- - '*/*'
- parameters:
- - in: body
- name: body
- description: body
- required: false
- schema:
- type: object
- additionalProperties:
- type: string
- responses:
- '200':
- description: OK
- schema:
- type: object
- '201':
- description: Created
- '401':
- description: Unauthorized
- '403':
- description: Forbidden
- '404':
- description: Not Found
- deprecated: false
- /actuator/metrics:
- get:
- tags:
- - operation-handler
- summary: handle
- operationId: handleUsingGET_7
- produces:
- - application/vnd.spring-boot.actuator.v3+json
- - application/json
- - application/vnd.spring-boot.actuator.v2+json
- parameters:
- - in: body
- name: body
- description: body
- required: false
- schema:
- type: object
- additionalProperties:
- type: string
- responses:
- '200':
- description: OK
- schema:
- type: object
- '401':
- description: Unauthorized
- '403':
- description: Forbidden
- '404':
- description: Not Found
- deprecated: false
- '/actuator/metrics/{requiredMetricName}':
- get:
- tags:
- - operation-handler
- summary: handle
- operationId: handleUsingGET_6
- produces:
- - application/vnd.spring-boot.actuator.v3+json
- - application/json
- - application/vnd.spring-boot.actuator.v2+json
- parameters:
- - in: body
- name: body
- description: body
- required: false
- schema:
- type: object
- additionalProperties:
- type: string
- responses:
- '200':
- description: OK
- schema:
- type: object
- '401':
- description: Unauthorized
- '403':
- description: Forbidden
- '404':
- description: Not Found
- deprecated: false
/policies:
get:
tags:
$ref: '#/definitions/ServiceRegistrationInfo'
responses:
'200':
- description: OK
+ description: Service updated
schema:
type: string
'201':
- description: Created
+ description: Service created
+ schema:
+ type: string
'400':
description: Cannot parse the ServiceRegistrationInfo
schema:
description: Not Found
deprecated: false
definitions:
- Link:
- type: object
- properties:
- href:
- type: string
- templated:
- type: boolean
- title: Link
- 'Map«string,Link»':
- type: object
- title: 'Map«string,Link»'
- additionalProperties:
- $ref: '#/definitions/Link'
Mono«ResponseEntity«object»»:
type: object
title: Mono«ResponseEntity«object»»
format: int64
description: time since last invocation by the service
title: ServiceStatus
+
@Configuration
class BeanFactory {
+ private final ApplicationConfig applicationConfig = new ApplicationConfig();
+
@Bean
public Policies getPolicies() {
return new Policies();
@Bean
public ApplicationConfig getApplicationConfig() {
- return new ApplicationConfig();
+ return this.applicationConfig;
}
@Bean
@Bean
A1ClientFactory getA1ClientFactory() {
- return new A1ClientFactory(getApplicationConfig());
+ return new A1ClientFactory(this.applicationConfig);
}
@Bean
.paths(PathSelectors.any()) //
.paths(Predicates.not(PathSelectors.regex("/error"))) //
// this endpoint is not implemented, but was visible for Swagger
+ .paths(Predicates.not(PathSelectors.regex("/actuator.*"))) //
+ // this endpoint is implemented by spring framework, exclude for now
.build();
}
}
@Before("execution(* org.oransc.policyagent..*(..)))")
- public void entryLog(final JoinPoint joinPoint) throws Throwable {
+ public void entryLog(final JoinPoint joinPoint) {
logger.trace("Entering method: {}", joinPoint.getSignature().getName());
}
@After("execution(* org.oransc.policyagent..*(..)))")
- public void exitLog(final JoinPoint joinPoint) throws Throwable {
+ public void exitLog(final JoinPoint joinPoint) {
logger.trace("Exiting method: {}", joinPoint.getSignature().getName());
}
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
+/**
+ * Common interface for 'A1' Policy access. Implementations of this interface
+ * adapts to the different southbound REST APIs supported.
+ */
public interface A1Client {
public enum A1ProtocolType {
UNKNOWN, //
- STD_V1_1, // version 1.1
- OSC_V1, //
- SDNC_OSC, //
+ STD_V1_1, // STD A1 version 1.1
+ OSC_V1, // OSC 'A1'
+ SDNC_OSC_STD_V1_1, // SDNC_OSC with STD A1 version 1.1 southbound
+ SDNC_OSC_OSC_V1, // SDNC_OSC with OSC 'A1' southbound
SDNC_ONAP
}
return new StdA1ClientVersion1(ric.getConfig());
} else if (version == A1ProtocolType.OSC_V1) {
return new OscA1Client(ric.getConfig());
- } else if (version == A1ProtocolType.SDNC_OSC) {
- return new SdncOscA1Client(ric.getConfig(), appConfig.getA1ControllerBaseUrl(),
+ } else if (version == A1ProtocolType.SDNC_OSC_STD_V1_1 || version == A1ProtocolType.SDNC_OSC_OSC_V1) {
+ return new SdncOscA1Client(version, ric.getConfig(), appConfig.getA1ControllerBaseUrl(),
appConfig.getA1ControllerUsername(), appConfig.getA1ControllerPassword());
} else if (version == A1ProtocolType.SDNC_ONAP) {
return new SdncOnapA1Client(ric.getConfig(), appConfig.getA1ControllerBaseUrl(),
if (ric.getProtocolVersion() == A1ProtocolType.UNKNOWN) {
return fetchVersion(createClient(ric, A1ProtocolType.STD_V1_1)) //
.onErrorResume(notUsed -> fetchVersion(createClient(ric, A1ProtocolType.OSC_V1))) //
- .onErrorResume(notUsed -> fetchVersion(createClient(ric, A1ProtocolType.SDNC_OSC))) //
+ .onErrorResume(notUsed -> fetchVersion(createClient(ric, A1ProtocolType.SDNC_OSC_STD_V1_1))) //
.onErrorResume(notUsed -> fetchVersion(createClient(ric, A1ProtocolType.SDNC_ONAP))) //
.doOnNext(ric::setProtocolVersion)
.doOnNext(version -> logger.debug("Established protocol version:{} for Ric: {}", version, ric.name())) //
}
private Mono<A1ProtocolType> fetchVersion(A1Client a1Client) {
- return Mono.just(a1Client) //
- .flatMap(client -> a1Client.getProtocolVersion());
+ return a1Client.getProtocolVersion();
}
}
package org.oransc.policyagent.clients;
-import java.util.Optional;
-
-import org.immutables.gson.Gson;
-import org.immutables.value.Value;
-
-@Value.Immutable
-@Gson.TypeAdapters
-interface SdncOscAdapterInput {
- public String nearRtRicUrl();
-
- public Optional<String> policyTypeId();
+/**
+ * Builder for A1 influenced REST APIs
+ */
+interface A1UriBuilder {
+ String createPutPolicyUri(String type, String policyId);
- public Optional<String> policyId();
+ String createDeleteUri(String type, String policyId);
- public Optional<String> policy();
+ String createGetPolicyStatusUri(String type, String policyId);
}
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
import reactor.core.publisher.Mono;
+/**
+ * Generic reactive REST client.
+ */
public class AsyncRestClient {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final WebClient client;
import org.oransc.policyagent.repository.Policy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
+/**
+ * Client for accessing OSC A1 REST API
+ */
+@SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
public class OscA1Client implements A1Client {
- private static final String URL_PREFIX = "/a1-p";
- private static final String POLICY_TYPES = "/policytypes";
- private static final String CREATE_SCHEMA = "create_schema";
- private static final String TITLE = "title";
+ public static class UriBuilder implements A1UriBuilder {
+ private final RicConfig ricConfig;
+
+ public UriBuilder(RicConfig ricConfig) {
+ this.ricConfig = ricConfig;
+ }
+
+ @Override
+ public String createPutPolicyUri(String type, String policyId) {
+ return createPolicyUri(type, policyId);
+ }
- private static final String HEALTHCHECK = "/healthcheck";
+ /**
+ * /a1-p/policytypes/{policy_type_id}/policies
+ */
+ public String createGetPolicyIdsUri(String type) {
+ return createPolicyTypeUri(type) + "/policies";
+ }
- private static final UriComponentsBuilder POLICY_TYPE_SCHEMA_URI =
- UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}");
+ @Override
+ public String createDeleteUri(String type, String policyId) {
+ return createPolicyUri(type, policyId);
+ }
- private static final UriComponentsBuilder POLICY_URI =
- UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}/policies/{policy-id}");
+ /**
+ * ​/a1-p​/policytypes​/{policy_type_id}​/policies​/{policy_instance_id}​/status
+ */
+ @Override
+ public String createGetPolicyStatusUri(String type, String policyId) {
+ return createPolicyUri(type, policyId) + "/status";
+ }
- private static final UriComponentsBuilder POLICY_IDS_URI =
- UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}/policies");
+ /**
+ * ​/a1-p​/healthcheck
+ */
+ public String createHealtcheckUri() {
+ return baseUri() + "/healthcheck";
+ }
- private static final UriComponentsBuilder POLICY_STATUS_URI =
- UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}/policies/{policy-id}/status");
+ /**
+ * /a1-p/policytypes/{policy_type_id}
+ */
+ public String createGetSchemaUri(String type) {
+ return this.createPolicyTypeUri(type);
+ }
- private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ /**
+ * ​/a1-p​/policytypes​/{policy_type_id}
+ */
+ public String createPolicyTypesUri() {
+ return baseUri() + "/policytypes";
+ }
+
+ /**
+ * ​/a1-p​/policytypes​/{policy_type_id}​/policies​/{policy_instance_id}
+ */
+ private String createPolicyUri(String type, String id) {
+ return createPolicyTypeUri(type) + "/policies/" + id;
+ }
+
+ /**
+ * /a1-p/policytypes/{policy_type_id}
+ */
+ private String createPolicyTypeUri(String type) {
+ return createPolicyTypesUri() + "/" + type;
+ }
+
+ private String baseUri() {
+ return ricConfig.baseUrl() + "/a1-p";
+ }
+ }
+ private static final String TITLE = "title";
+ private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final AsyncRestClient restClient;
+ private final UriBuilder uri;
public OscA1Client(RicConfig ricConfig) {
- String baseUrl = ricConfig.baseUrl() + URL_PREFIX;
- this.restClient = new AsyncRestClient(baseUrl);
- if (logger.isDebugEnabled()) {
- logger.debug("OscA1Client for ric: {}", ricConfig.name());
- }
+ this(ricConfig, new AsyncRestClient(""));
}
- public OscA1Client(AsyncRestClient restClient) {
+ public OscA1Client(RicConfig ricConfig, AsyncRestClient restClient) {
this.restClient = restClient;
+ logger.debug("OscA1Client for ric: {}", ricConfig.name());
+
+ uri = new UriBuilder(ricConfig);
}
@Override
@Override
public Mono<String> getPolicyTypeSchema(String policyTypeId) {
- String uri = POLICY_TYPE_SCHEMA_URI.buildAndExpand(policyTypeId).toUriString();
- return restClient.get(uri) //
+ String schemaUri = uri.createGetSchemaUri(policyTypeId);
+ return restClient.get(schemaUri) //
.flatMap(response -> getCreateSchema(response, policyTypeId));
}
@Override
public Mono<String> putPolicy(Policy policy) {
- String uri = POLICY_URI.buildAndExpand(policy.type().name(), policy.id()).toUriString();
- return restClient.put(uri, policy.json());
+ String policyUri = this.uri.createPutPolicyUri(policy.type().name(), policy.id());
+ return restClient.put(policyUri, policy.json());
}
@Override
@Override
public Mono<A1ProtocolType> getProtocolVersion() {
- return restClient.get(HEALTHCHECK) //
+ return restClient.get(uri.createHealtcheckUri()) //
.flatMap(notUsed -> Mono.just(A1ProtocolType.OSC_V1));
}
@Override
public Mono<String> getPolicyStatus(Policy policy) {
- String uri = POLICY_STATUS_URI.buildAndExpand(policy.type().name(), policy.id()).toUriString();
- return restClient.get(uri);
+ String statusUri = uri.createGetPolicyStatusUri(policy.type().name(), policy.id());
+ return restClient.get(statusUri);
}
private Flux<String> getPolicyTypeIds() {
- return restClient.get(POLICY_TYPES) //
- .flatMapMany(JsonHelper::parseJsonArrayOfString);
+ return restClient.get(uri.createPolicyTypesUri()) //
+ .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
}
private Flux<String> getPolicyIdentitiesByType(String typeId) {
- return restClient.get(POLICY_IDS_URI.buildAndExpand(typeId).toUriString()) //
- .flatMapMany(JsonHelper::parseJsonArrayOfString);
+ return restClient.get(uri.createGetPolicyIdsUri(typeId)) //
+ .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
}
private Mono<String> getCreateSchema(String policyTypeResponse, String policyTypeId) {
try {
JSONObject obj = new JSONObject(policyTypeResponse);
- JSONObject schemaObj = obj.getJSONObject(CREATE_SCHEMA);
+ JSONObject schemaObj = obj.getJSONObject("create_schema");
schemaObj.put(TITLE, policyTypeId);
return Mono.just(schemaObj.toString());
} catch (Exception e) {
}
private Mono<String> deletePolicyById(String typeId, String policyId) {
- String uri = POLICY_URI.buildAndExpand(typeId, policyId).toUriString();
- return restClient.delete(uri);
+ String policyUri = uri.createDeleteUri(typeId, policyId);
+ return restClient.delete(policyUri);
}
private Flux<String> deletePoliciesForType(String typeId) {
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
-public class JsonHelper {
+/**
+ * Common json functionality used by the SDNC clients
+ */
+class SdncJsonHelper {
private static Gson gson = new GsonBuilder() //
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) //
.create();
- private JsonHelper() {
-
+ private SdncJsonHelper() {
}
public static Flux<String> parseJsonArrayOfString(String inputString) {
return Mono.error(ex);
}
}
-
- public static Mono<String> validateJson(String inputString) {
- try {
- new JSONObject(inputString);
- return Mono.just(inputString);
- } catch (JSONException ex) { // invalid json
- return Mono.error(ex);
- }
- }
}
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.oransc.policyagent.configuration.RicConfig;
import org.oransc.policyagent.repository.Policy;
import org.slf4j.Logger;
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<String> policyTypeId();
+
+ public Optional<String> policyInstanceId();
+
+ public Optional<String> policyInstance();
+
+ public Optional<List<String>> properties();
+ }
+
private static final String URL_PREFIX = "/A1-ADAPTER-API:";
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
public SdncOnapA1Client(RicConfig ricConfig, String baseUrl, String username, String password) {
this(ricConfig, username, password, new AsyncRestClient(baseUrl + "/restconf/operations"));
- if (logger.isDebugEnabled()) {
- logger.debug("SdncOnapA1Client for ric: {}, a1ControllerBaseUrl: {}", ricConfig.name(), baseUrl);
- }
+ logger.debug("SdncOnapA1Client for ric: {}, a1ControllerBaseUrl: {}", ricConfig.name(), baseUrl);
}
public SdncOnapA1Client(RicConfig ricConfig, String username, String password, AsyncRestClient restClient) {
.nearRtRicId(ricConfig.baseUrl()) //
.policyTypeId(policyTypeId) //
.build();
- String inputJsonString = JsonHelper.createInputJsonString(inputParams);
+ String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
logger.debug("POST getPolicyType inputJsonString = {}", inputJsonString);
return restClient
.postWithAuthHeader(URL_PREFIX + "getPolicyType", inputJsonString, a1ControllerUsername,
a1ControllerPassword) //
- .flatMap(response -> JsonHelper.getValueFromResponse(response, "policy-type")) //
- .flatMap(JsonHelper::extractPolicySchema);
+ .flatMap(response -> SdncJsonHelper.getValueFromResponse(response, "policy-type")) //
+ .flatMap(SdncJsonHelper::extractPolicySchema);
}
@Override
.properties(new ArrayList<String>()) //
.build();
- String inputJsonString = JsonHelper.createInputJsonString(inputParams);
+ String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
logger.debug("POST putPolicy inputJsonString = {}", inputJsonString);
return restClient.postWithAuthHeader(URL_PREFIX + "createPolicyInstance", inputJsonString, a1ControllerUsername,
SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(ricConfig.baseUrl()) //
.build();
- String inputJsonString = JsonHelper.createInputJsonString(inputParams);
+ String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
logger.debug("POST getPolicyTypeIdentities inputJsonString = {}", inputJsonString);
return restClient
.postWithAuthHeader("/A1-ADAPTER-API:getPolicyTypes", inputJsonString, a1ControllerUsername,
a1ControllerPassword) //
- .flatMap(response -> JsonHelper.getValueFromResponse(response, "policy-type-id-list")) //
- .flatMapMany(JsonHelper::parseJsonArrayOfString);
+ .flatMap(response -> SdncJsonHelper.getValueFromResponse(response, "policy-type-id-list")) //
+ .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
}
private Flux<String> getPolicyIdentitiesByType(String policyTypeId) {
.nearRtRicId(ricConfig.baseUrl()) //
.policyTypeId(policyTypeId) //
.build();
- String inputJsonString = JsonHelper.createInputJsonString(inputParams);
+ String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
logger.debug("POST getPolicyIdentities inputJsonString = {}", inputJsonString);
return restClient
.postWithAuthHeader("/A1-ADAPTER-API:getPolicyInstances", inputJsonString, a1ControllerUsername,
a1ControllerPassword) //
- .flatMap(response -> JsonHelper.getValueFromResponse(response, "policy-instance-id-list")) //
- .flatMapMany(JsonHelper::parseJsonArrayOfString);
+ .flatMap(response -> SdncJsonHelper.getValueFromResponse(response, "policy-instance-id-list")) //
+ .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
}
private Flux<String> deletePoliciesForType(String typeId) {
.policyTypeId(policyTypeId) //
.policyInstanceId(policyId) //
.build();
- String inputJsonString = JsonHelper.createInputJsonString(inputParams);
+ String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
logger.debug("POST deletePolicy inputJsonString = {}", inputJsonString);
return restClient.postWithAuthHeader("/A1-ADAPTER-API:deletePolicyInstance", inputJsonString,
+++ /dev/null
-/*-
- * ========================LICENSE_START=================================
- * O-RAN-SC
- * %%
- * Copyright (C) 2020 Nordix Foundation
- * %%
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * 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.oransc.policyagent.clients;
-
-import java.util.List;
-import java.util.Optional;
-
-import org.immutables.gson.Gson;
-import org.immutables.value.Value;
-
-@Value.Immutable
-@Gson.TypeAdapters
-interface SdncOnapAdapterInput {
- public String nearRtRicId();
-
- public Optional<String> policyTypeId();
-
- public Optional<String> policyInstanceId();
-
- public Optional<String> policyInstance();
-
- public Optional<List<String>> properties();
-}
package org.oransc.policyagent.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.oransc.policyagent.configuration.RicConfig;
import org.oransc.policyagent.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 {
- private static final String URL_PREFIX = "/A1-ADAPTER-API:";
+ @Value.Immutable
+ @org.immutables.gson.Gson.TypeAdapters
+ public interface AdapterRequest {
+ public String nearRtRicUrl();
+
+ public Optional<String> body();
+ }
+
+ @Value.Immutable
+ @org.immutables.gson.Gson.TypeAdapters
+ public interface AdapterResponse {
+ public String 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 String UNHANDELED_PROTOCOL = "Bug, unhandeled protocoltype: ";
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final String a1ControllerUsername;
private final String a1ControllerPassword;
- private final RicConfig ricConfig;
private final AsyncRestClient restClient;
-
- public SdncOscA1Client(RicConfig ricConfig, String baseUrl, String username, String password) {
- this(ricConfig, username, password, new AsyncRestClient(baseUrl + "/restconf/operations"));
- logger.debug("SdncOscA1Client for ric: {}, a1ControllerBaseUrl: {}", ricConfig.name(), baseUrl);
+ private final RicConfig ricConfig;
+ private final A1ProtocolType protocolType;
+
+ /**
+ * Constructor
+ *
+ * @param protocolType the southbound protocol of the controller. Supported
+ * protocols are SDNC_OSC_STD_V1_1 and SDNC_OSC_OSC_V1
+ * @param ricConfig
+ * @param controllerBaseUrl the base URL of the SDNC controller
+ * @param username username to accesss the SDNC controller
+ * @param password password to accesss the SDNC controller
+ */
+ public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, String controllerBaseUrl, String username,
+ String password) {
+ this(protocolType, ricConfig, username, password,
+ new AsyncRestClient(controllerBaseUrl + "/restconf/operations"));
+ logger.debug("SdncOscA1Client for ric: {}, a1ControllerBaseUrl: {}", ricConfig.name(), controllerBaseUrl);
}
- public SdncOscA1Client(RicConfig ricConfig, String username, String password, AsyncRestClient restClient) {
- this.ricConfig = ricConfig;
+ public SdncOscA1Client(A1ProtocolType protocolType, RicConfig ricConfig, String username, String password,
+ AsyncRestClient restClient) {
this.a1ControllerUsername = username;
this.a1ControllerPassword = password;
this.restClient = restClient;
+ this.ricConfig = ricConfig;
+ this.protocolType = protocolType;
+
}
@Override
public Mono<List<String>> getPolicyTypeIdentities() {
- return Mono.just(Arrays.asList(""));
+ if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
+ return Mono.just(Arrays.asList(""));
+ } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
+ OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
+ final String ricUrl = uri.createPolicyTypesUri();
+ return post(GET_POLICY_RPC, ricUrl, Optional.empty()) //
+ .flatMapMany(SdncJsonHelper::parseJsonArrayOfString) //
+ .collectList();
+ }
+ throw new NullPointerException(UNHANDELED_PROTOCOL + this.protocolType);
}
@Override
@Override
public Mono<String> getPolicyTypeSchema(String policyTypeId) {
- return Mono.just("{}");
+ if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
+ return Mono.just("{}");
+ } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
+ OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
+ final String ricUrl = uri.createGetSchemaUri(policyTypeId);
+ return post(GET_POLICY_RPC, ricUrl, Optional.empty());
+ }
+ throw new NullPointerException(UNHANDELED_PROTOCOL + this.protocolType);
}
@Override
public Mono<String> putPolicy(Policy policy) {
- SdncOscAdapterInput inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(ricConfig.baseUrl()) //
- .policyTypeId(policy.type().name()) //
- .policyId(policy.id()) //
- .policy(policy.json()) //
- .build();
- String inputJsonString = JsonHelper.createInputJsonString(inputParams);
- return restClient
- .postWithAuthHeader(URL_PREFIX + "putPolicy", inputJsonString, a1ControllerUsername, a1ControllerPassword)
- .flatMap(response -> JsonHelper.getValueFromResponse(response, "returned-policy")) //
- .flatMap(JsonHelper::validateJson);
+ final String ricUrl = getUriBuilder().createPutPolicyUri(policy.type().name(), policy.id());
+ return post("putA1Policy", ricUrl, Optional.of(policy.json()));
}
@Override
public Mono<String> deletePolicy(Policy policy) {
- return deletePolicyById(policy.id());
+ return deletePolicyById(policy.type().name(), policy.id());
}
@Override
public Flux<String> deleteAllPolicies() {
- return getPolicyIds() //
- .flatMap(this::deletePolicyById); //
+ if (this.protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
+ return getPolicyIds() //
+ .flatMap(policyId -> deletePolicyById("", policyId)); //
+ } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
+ OscA1Client.UriBuilder uriBuilder = new OscA1Client.UriBuilder(ricConfig);
+ return getPolicyTypeIdentities() //
+ .flatMapMany(Flux::fromIterable)
+ .flatMap(type -> post(GET_POLICY_RPC, uriBuilder.createGetPolicyIdsUri(type), Optional.empty())) //
+ .flatMap(SdncJsonHelper::parseJsonArrayOfString);
+ }
+ throw new NullPointerException(UNHANDELED_PROTOCOL + this.protocolType);
}
@Override
public Mono<A1ProtocolType> getProtocolVersion() {
- return getPolicyIdentities() //
- .flatMap(x -> Mono.just(A1ProtocolType.SDNC_OSC));
+ return tryStdProtocolVersion() //
+ .onErrorResume(t -> tryOscProtocolVersion());
}
@Override
public Mono<String> getPolicyStatus(Policy policy) {
- SdncOscAdapterInput inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(ricConfig.baseUrl()) //
- .policyId(policy.id()) //
- .build();
- String inputJsonString = JsonHelper.createInputJsonString(inputParams);
- logger.debug("POST getPolicyStatus inputJsonString = {}", inputJsonString);
+ final String ricUrl = getUriBuilder().createGetPolicyStatusUri(policy.type().name(), policy.id());
+ return post("getA1PolicyStatus", ricUrl, Optional.empty());
+ }
- return restClient
- .postWithAuthHeader(URL_PREFIX + "getPolicyStatus", inputJsonString, a1ControllerUsername,
- a1ControllerPassword) //
- .flatMap(response -> JsonHelper.getValueFromResponse(response, "policy-status"));
+ private A1UriBuilder getUriBuilder() {
+ if (protocolType == A1ProtocolType.SDNC_OSC_STD_V1_1) {
+ return new StdA1ClientVersion1.UriBuilder(ricConfig);
+ } else if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
+ return new OscA1Client.UriBuilder(ricConfig);
+ }
+ throw new NullPointerException(UNHANDELED_PROTOCOL + this.protocolType);
+ }
+
+ private Mono<A1ProtocolType> 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<A1ProtocolType> tryStdProtocolVersion() {
+ 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 Flux<String> getPolicyIds() {
- SdncOscAdapterInput inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(ricConfig.baseUrl()) //
+ 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 if (this.protocolType == A1ProtocolType.SDNC_OSC_OSC_V1) {
+ OscA1Client.UriBuilder uri = new OscA1Client.UriBuilder(ricConfig);
+ return getPolicyTypeIdentities() //
+ .flatMapMany(Flux::fromIterable)
+ .flatMap(type -> post(GET_POLICY_RPC, uri.createGetPolicyIdsUri(type), Optional.empty())) //
+ .flatMap(SdncJsonHelper::parseJsonArrayOfString);
+ }
+ throw new NullPointerException(UNHANDELED_PROTOCOL + this.protocolType);
+ }
+
+ private Mono<String> deletePolicyById(String type, String policyId) {
+ final String ricUrl = getUriBuilder().createDeleteUri(type, policyId);
+ return post("deleteA1Policy", ricUrl, Optional.empty());
+ }
+
+ private Mono<String> post(String rpcName, String ricUrl, Optional<String> body) {
+ AdapterRequest inputParams = ImmutableAdapterRequest.builder() //
+ .nearRtRicUrl(ricUrl) //
+ .body(body) //
.build();
- String inputJsonString = JsonHelper.createInputJsonString(inputParams);
+ final String inputJsonString = SdncJsonHelper.createInputJsonString(inputParams);
+
return restClient
- .postWithAuthHeader(URL_PREFIX + "getPolicyIdentities", inputJsonString, a1ControllerUsername,
- a1ControllerPassword) //
- .flatMap(response -> JsonHelper.getValueFromResponse(response, "policy-id-list")) //
- .flatMapMany(JsonHelper::parseJsonArrayOfString);
+ .postWithAuthHeader(controllerUrl(rpcName), inputJsonString, a1ControllerUsername, a1ControllerPassword)
+ .flatMap(this::extractResponseBody);
}
- private Mono<String> deletePolicyById(String policyId) {
- SdncOscAdapterInput inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(ricConfig.baseUrl()) //
- .policyId(policyId) //
- .build();
+ private Mono<String> extractResponseBody(String response) {
+ AdapterResponse output = gson.fromJson(response, ImmutableAdapterResponse.class);
+ String body = output.body();
+ if (HttpStatus.valueOf(output.httpStatus()).is2xxSuccessful()) {
+ return Mono.just(body);
+ }
+ byte[] responseBodyBytes = body.getBytes(StandardCharsets.UTF_8);
+ WebClientResponseException e = new WebClientResponseException(output.httpStatus(), "statusText", null,
+ responseBodyBytes, StandardCharsets.UTF_8, null);
+
+ return Mono.error(e);
+ }
- String inputJsonString = JsonHelper.createInputJsonString(inputParams);
- return restClient.postWithAuthHeader(URL_PREFIX + "deletePolicy", inputJsonString, a1ControllerUsername,
- a1ControllerPassword);
+ private String controllerUrl(String rpcName) {
+ return "/A1-ADAPTER-API:" + rpcName;
}
}
import org.oransc.policyagent.configuration.RicConfig;
import org.oransc.policyagent.repository.Policy;
-import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
+/**
+ * Client for accessing standard A1 REST API version 1.1
+ */
public class StdA1ClientVersion1 implements A1Client {
+
+ public static class UriBuilder implements A1UriBuilder {
+
+ private final RicConfig ricConfig;
+
+ public UriBuilder(RicConfig ricConfig) {
+ this.ricConfig = ricConfig;
+ }
+
+ /**
+ * /A1-P/v1/policies/{policyId}
+ */
+ @Override
+ public String createPutPolicyUri(String type, String policyId) {
+ return policiesBaseUri() + policyId;
+ }
+
+ /**
+ * /A1-P/v1/policies
+ */
+ public String createGetPolicyIdsUri() {
+ return baseUri() + "/policies";
+ }
+
+ /**
+ * /A1-P/v1/policies/{policyId}
+ */
+ @Override
+ public String createDeleteUri(String type, String policyId) {
+ return policiesBaseUri() + policyId;
+ }
+
+ /**
+ * /A1-P/v1/policies/{policyId}/status
+ */
+ public String createGetPolicyStatusUri(String type, String policyId) {
+ return policiesBaseUri() + policyId + "/status";
+ }
+
+ private String baseUri() {
+ return ricConfig.baseUrl() + "/A1-P/v1";
+ }
+
+ private String policiesBaseUri() {
+ return createGetPolicyIdsUri() + "/";
+ }
+ }
+
private final AsyncRestClient restClient;
+ private final UriBuilder uri;
public StdA1ClientVersion1(RicConfig ricConfig) {
- final String urlPrefix = "/A1-P/v1";
- String baseUrl = ricConfig.baseUrl() + urlPrefix;
- this.restClient = new AsyncRestClient(baseUrl);
+ this(new AsyncRestClient(""), ricConfig);
}
- public StdA1ClientVersion1(AsyncRestClient restClient) {
+ public StdA1ClientVersion1(AsyncRestClient restClient, RicConfig ricConfig) {
this.restClient = restClient;
+ this.uri = new UriBuilder(ricConfig);
}
@Override
@Override
public Mono<String> putPolicy(Policy policy) {
- final UriComponentsBuilder policyUri = UriComponentsBuilder.fromPath("/policies/{policy-id}");
- final String uri = policyUri.buildAndExpand(policy.id()).toUriString();
- return restClient.put(uri, policy.json()) //
- .flatMap(JsonHelper::validateJson);
+ return restClient.put(uri.createPutPolicyUri(policy.type().name(), policy.id()), policy.json());
}
@Override
@Override
public Mono<String> getPolicyStatus(Policy policy) {
- final UriComponentsBuilder builder = UriComponentsBuilder.fromPath("/policies/{policy-id}/status");
- String uri = builder.buildAndExpand(policy.id()).toUriString();
- return restClient.get(uri);
+ return restClient.get(uri.createGetPolicyStatusUri(policy.type().name(), policy.id()));
}
private Flux<String> getPolicyIds() {
- final String uri = "/policies";
- return restClient.get(uri) //
- .flatMapMany(JsonHelper::parseJsonArrayOfString);
+ return restClient.get(uri.createGetPolicyIdsUri()) //
+ .flatMapMany(SdncJsonHelper::parseJsonArrayOfString);
}
private Mono<String> deletePolicyById(String policyId) {
- final UriComponentsBuilder builder = UriComponentsBuilder.fromPath("/policies/{policy-id}");
- String uri = builder.buildAndExpand(policyId).toUriString();
- return restClient.delete(uri);
+ return restClient.delete(uri.createDeleteUri("", policyId));
}
}
import javax.validation.constraints.NotNull;
-import lombok.Getter;
-
+import org.immutables.gson.Gson;
+import org.immutables.value.Value;
import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
import org.oransc.policyagent.exceptions.ServiceException;
import org.springframework.http.MediaType;
+/**
+ * Parser for the Json representing of the component configuration.
+ */
public class ApplicationConfigParser {
private static final String CONFIG = "config";
- @Getter
- private List<RicConfig> ricConfigs;
- @Getter
- private Properties dmaapPublisherConfig = new Properties();
- @Getter
- private Properties dmaapConsumerConfig = new Properties();
+ @Value.Immutable
+ @Gson.TypeAdapters
+ public interface ConfigParserResult {
+ List<RicConfig> ricConfigs();
+
+ Properties dmaapPublisherConfig();
+
+ Properties dmaapConsumerConfig();
+ }
+
+ public ConfigParserResult parse(JsonObject root) throws ServiceException {
+
+ Properties dmaapPublisherConfig = new Properties();
+ Properties dmaapConsumerConfig = new Properties();
- public void parse(JsonObject root) throws ServiceException {
JsonObject agentConfigJson = root.getAsJsonObject(CONFIG);
- ricConfigs = parseRics(agentConfigJson);
+ List<RicConfig> ricConfigs = parseRics(agentConfigJson);
JsonObject json = agentConfigJson.getAsJsonObject("streams_publishes");
if (json != null) {
- this.dmaapPublisherConfig = parseDmaapConfig(json);
+ dmaapPublisherConfig = parseDmaapConfig(json);
}
json = agentConfigJson.getAsJsonObject("streams_subscribes");
if (json != null) {
- this.dmaapConsumerConfig = parseDmaapConfig(json);
+ dmaapConsumerConfig = parseDmaapConfig(json);
}
+ return ImmutableConfigParserResult.builder() //
+ .dmaapConsumerConfig(dmaapConsumerConfig) //
+ .dmaapPublisherConfig(dmaapPublisherConfig) //
+ .ricConfigs(ricConfigs) //
+ .build();
}
private List<RicConfig> parseRics(JsonObject config) throws ServiceException {
import org.springframework.stereotype.Component;
/**
- * The class fetched incoming requests from DMAAP on regular intervals. Each
+ * The class fetches incoming requests from DMAAP on regular intervals. Each
* received request is proceesed by DmaapMessageHandler.
*/
@Component
package org.oransc.policyagent.exceptions;
-public class EnvironmentLoaderException extends Exception {
+public class EnvironmentLoaderException extends ServiceException {
private static final long serialVersionUID = 1L;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
+/**
+ * This class reads a few environment variables used for locating the Consul
+ * (Config Binding Service).
+ */
class EnvironmentProcessor {
private static final int DEFAULT_CONSUL_PORT = 8500;
import reactor.core.publisher.Mono;
/**
- * Regularly refreshes the configuration from Consul.
+ * Regularly refreshes the configuration from Consul or from a local
+ * configuration file.
*/
@Component
public class RefreshConfigTask {
return Mono.empty();
}
- private Mono<ApplicationConfigParser> parseConfiguration(JsonObject jsonObject) {
+ private Mono<ApplicationConfigParser.ConfigParserResult> parseConfiguration(JsonObject jsonObject) {
try {
ApplicationConfigParser parser = new ApplicationConfigParser();
- parser.parse(jsonObject);
- return Mono.just(parser);
+ return Mono.just(parser.parse(jsonObject));
} catch (ServiceException e) {
logger.error("Could not parse configuration {}", e.toString(), e);
return Mono.error(e);
}
}
- private Flux<RicConfigUpdate> updateConfig(ApplicationConfigParser config) {
- return this.appConfig.setConfiguration(config.getRicConfigs(), config.getDmaapPublisherConfig(),
- config.getDmaapConsumerConfig());
+ private Flux<RicConfigUpdate> updateConfig(ApplicationConfigParser.ConfigParserResult config) {
+ return this.appConfig.setConfiguration(config.ricConfigs(), config.dmaapPublisherConfig(),
+ config.dmaapConsumerConfig());
}
boolean configFileExists() {
/**
* Regularly checks the existing rics towards the local repository to keep it
- * consistent.
+ * consistent. When the policy types or instances in the Near-RT RIC is not
+ * consistent, a synchronization is performed.
*/
@Component
@EnableScheduling
assertTrue(createClient(A1ProtocolType.STD_V1_1) instanceof StdA1ClientVersion1);
assertTrue(createClient(A1ProtocolType.OSC_V1) instanceof OscA1Client);
assertTrue(createClient(A1ProtocolType.SDNC_ONAP) instanceof SdncOnapA1Client);
- assertTrue(createClient(A1ProtocolType.SDNC_OSC) instanceof SdncOscA1Client);
+ assertTrue(createClient(A1ProtocolType.SDNC_OSC_STD_V1_1) instanceof SdncOscA1Client);
+ assertTrue(createClient(A1ProtocolType.SDNC_OSC_OSC_V1) instanceof SdncOscA1Client);
assertTrue(createClient(A1ProtocolType.UNKNOWN) == null);
}
package org.oransc.policyagent.clients;
+import static org.junit.jupiter.api.Assertions.assertEquals;
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.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
+import org.oransc.policyagent.configuration.ImmutableRicConfig;
+import org.oransc.policyagent.configuration.RicConfig;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@ExtendWith(MockitoExtension.class)
public class OscA1ClientTest {
+
private static final String RIC_URL = "RicUrl";
- private static final String POLICYTYPES_IDENTITIES_URL = "/policytypes";
- private static final String POLICIES_IDENTITIES_URL = "/policies";
- private static final String POLICYTYPES_URL = "/policytypes/";
- private static final String POLICIES_URL = "/policies/";
+ private static final String RIC_BASE_URL = "RicBaseUrl/a1-p";
+
+ private static final String POLICYTYPES_IDENTITIES_URL = RIC_BASE_URL + "/policytypes";
+ private static final String POLICIES = "/policies";
+ private static final String POLICYTYPES_URL = RIC_BASE_URL + "/policytypes/";
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\"}";
@BeforeEach
public void init() {
+ RicConfig ricConfig = ImmutableRicConfig.builder() //
+ .name("name") //
+ .baseUrl("RicBaseUrl") //
+ .managedElementIds(new ArrayList<>()) //
+ .build();
asyncRestClientMock = mock(AsyncRestClient.class);
- clientUnderTest = new OscA1Client(asyncRestClientMock);
+ clientUnderTest = new OscA1Client(ricConfig, asyncRestClientMock);
}
@Test
when(asyncRestClientMock.get(anyString())).thenReturn(policyTypeIdsResp).thenReturn(policyIdsType1Resp)
.thenReturn(policyIdsType2Resp);
- Mono<List<String>> returnedMono = clientUnderTest.getPolicyIdentities();
- StepVerifier.create(returnedMono).expectNext(Arrays.asList(POLICY_1_ID, POLICY_2_ID)).expectComplete().verify();
+ List<String> returned = clientUnderTest.getPolicyIdentities().block();
+
+ assertEquals(2, returned.size(), "");
verify(asyncRestClientMock).get(POLICYTYPES_IDENTITIES_URL);
- verify(asyncRestClientMock).get(POLICYTYPES_URL + POLICY_TYPE_1_ID + POLICIES_IDENTITIES_URL);
- verify(asyncRestClientMock).get(POLICYTYPES_URL + POLICY_TYPE_2_ID + POLICIES_IDENTITIES_URL);
+ verify(asyncRestClientMock).get(POLICYTYPES_URL + POLICY_TYPE_1_ID + POLICIES);
+ verify(asyncRestClientMock).get(POLICYTYPES_URL + POLICY_TYPE_2_ID + POLICIES);
}
@Test
public void testPutPolicy() {
when(asyncRestClientMock.put(anyString(), anyString())).thenReturn(Mono.empty());
- Mono<String> returnedMono = clientUnderTest
- .putPolicy(A1ClientHelper.createPolicy(RIC_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID));
- verify(asyncRestClientMock).put(POLICYTYPES_URL + POLICY_TYPE_1_ID + POLICIES_URL + POLICY_1_ID,
+ clientUnderTest
+ .putPolicy(A1ClientHelper.createPolicy(RIC_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID)).block();
+ verify(asyncRestClientMock).put(POLICYTYPES_URL + POLICY_TYPE_1_ID + POLICIES + "/" + POLICY_1_ID,
POLICY_JSON_VALID);
- StepVerifier.create(returnedMono).expectComplete().verify();
}
@Test
Mono<String> returnedMono = clientUnderTest
.deletePolicy(A1ClientHelper.createPolicy(RIC_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID));
- verify(asyncRestClientMock).delete(POLICYTYPES_URL + POLICY_TYPE_1_ID + POLICIES_URL + POLICY_1_ID);
+ verify(asyncRestClientMock).delete(POLICYTYPES_URL + POLICY_TYPE_1_ID + POLICIES + "/" + POLICY_1_ID);
StepVerifier.create(returnedMono).expectComplete().verify();
}
Flux<String> returnedFlux = clientUnderTest.deleteAllPolicies();
StepVerifier.create(returnedFlux).expectComplete().verify();
verify(asyncRestClientMock).get(POLICYTYPES_IDENTITIES_URL);
- verify(asyncRestClientMock).get(POLICYTYPES_URL + POLICY_TYPE_1_ID + POLICIES_IDENTITIES_URL);
- verify(asyncRestClientMock).delete(POLICYTYPES_URL + POLICY_TYPE_1_ID + POLICIES_URL + POLICY_1_ID);
- verify(asyncRestClientMock).get(POLICYTYPES_URL + POLICY_TYPE_2_ID + POLICIES_IDENTITIES_URL);
- verify(asyncRestClientMock).delete(POLICYTYPES_URL + POLICY_TYPE_2_ID + POLICIES_URL + POLICY_2_ID);
+ verify(asyncRestClientMock).get(POLICYTYPES_URL + POLICY_TYPE_1_ID + POLICIES);
+ verify(asyncRestClientMock).delete(POLICYTYPES_URL + POLICY_TYPE_1_ID + POLICIES + "/" + POLICY_1_ID);
+ verify(asyncRestClientMock).get(POLICYTYPES_URL + POLICY_TYPE_2_ID + POLICIES);
+ verify(asyncRestClientMock).delete(POLICYTYPES_URL + POLICY_TYPE_2_ID + POLICIES + "/" + POLICY_2_ID);
}
}
@Test
public void testGetPolicyTypeIdentities() {
- SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
+ SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.build();
String inputJsonString = A1ClientHelper.createInputJsonString(inputParams);
@Test
public void testGetPolicyIdentities() {
- SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
+ SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.build();
String inputJsonStringGetTypeIds = A1ClientHelper.createInputJsonString(inputParams);
@Test
public void testGetValidPolicyType() {
- SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
+ SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.policyTypeId(POLICY_TYPE_1_ID) //
.build();
@Test
public void testGetInvalidPolicyType() {
- SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
+ SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.policyTypeId(POLICY_TYPE_1_ID) //
.build();
@Test
public void testPutPolicy() {
- SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
+ SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.policyTypeId(POLICY_TYPE_1_ID) //
.policyInstanceId(POLICY_1_ID) //
@Test
public void testDeletePolicy() {
- SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
+ SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.policyTypeId(POLICY_TYPE_1_ID) //
.policyInstanceId(POLICY_1_ID) //
@Test
public void testDeleteAllPolicies() {
- SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
+ SdncOnapA1Client.SdncOnapAdapterInput inputParams = ImmutableSdncOnapAdapterInput.builder() //
.nearRtRicId(RIC_1_URL) //
.build();
String inputJsonStringGetTypeIds = A1ClientHelper.createInputJsonString(inputParams);
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import com.google.gson.Gson;
+
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.oransc.policyagent.clients.A1Client.A1ProtocolType;
+import org.oransc.policyagent.clients.SdncOscA1Client.AdapterRequest;
+import org.oransc.policyagent.clients.SdncOscA1Client.AdapterResponse;
import org.oransc.policyagent.repository.Policy;
+import org.oransc.policyagent.repository.Ric;
+import org.springframework.web.reactive.function.client.WebClientResponseException;
-import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
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 POLICY_IDENTITIES_URL = "/A1-ADAPTER-API:getPolicyIdentities";
- private static final String PUT_POLICY_URL = "/A1-ADAPTER-API:putPolicy";
- private static final String DELETE_POLICY_URL = "/A1-ADAPTER-API:deletePolicy";
+ 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_2_ID = "policy2";
private static final String POLICY_JSON_VALID = "{\"scope\":{\"ueId\":\"ue1\"}}";
- private static final String POLICY_JSON_INVALID = "\"scope\":{\"ueId\":\"ue1\"}}";
SdncOscA1Client clientUnderTest;
@BeforeEach
public void init() {
asyncRestClientMock = mock(AsyncRestClient.class);
- clientUnderTest = new SdncOscA1Client(A1ClientHelper.createRic(RIC_1_URL).getConfig(), CONTROLLER_USERNAME,
+ Ric ric = A1ClientHelper.createRic(RIC_1_URL);
+ clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_STD_V1_1, ric.getConfig(), CONTROLLER_USERNAME,
CONTROLLER_PASSWORD, asyncRestClientMock);
}
@Test
- public void testGetPolicyTypeIdentities() {
+ public void testGetPolicyTypeIdentities_STD() {
List<String> policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block();
assertEquals(1, policyTypeIds.size(), "should hardcoded to one");
assertEquals("", policyTypeIds.get(0), "should hardcoded to empty");
}
@Test
- public void testGetPolicyIdentities() {
- SdncOscAdapterInput inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(RIC_1_URL) //
+ public void testGetPolicyTypeIdentities_OSC() {
+ clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
+ A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
+ CONTROLLER_USERNAME, CONTROLLER_PASSWORD, asyncRestClientMock);
+
+ String response = createResponse(Arrays.asList(POLICY_TYPE_1_ID));
+ whenAsyncPostThenReturn(Mono.just(response));
+
+ List<String> policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block();
+ assertEquals(1, policyTypeIds.size(), "");
+ assertEquals(POLICY_TYPE_1_ID, policyTypeIds.get(0), "");
+
+ String expUrl = RIC_1_URL + "/a1-p/policytypes";
+ AdapterRequest expectedParams = ImmutableAdapterRequest.builder() //
+ .nearRtRicUrl(expUrl) //
+ .build();
+ String expInput = A1ClientHelper.createInputJsonString(expectedParams);
+ verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
+ CONTROLLER_PASSWORD);
+
+ }
+
+ private String policiesUrl() {
+ return RIC_1_URL + "/A1-P/v1/policies";
+ }
+
+ private Gson gson() {
+ return SdncOscA1Client.gson;
+ }
+
+ private String createResponse(Object obj) {
+ AdapterResponse output = ImmutableAdapterResponse.builder() //
+ .body(gson().toJson(obj)) //
+ .httpStatus(200) //
.build();
- String inputJsonString = A1ClientHelper.createInputJsonString(inputParams);
- List<String> policyIds = Arrays.asList(POLICY_1_ID, POLICY_2_ID);
- Mono<String> policyIdsResp = A1ClientHelper.createOutputJsonResponse("policy-id-list", policyIds.toString());
- whenAsyncPostThenReturn(policyIdsResp);
+ return gson().toJson(output);
+ }
+
+ @Test
+ public void testGetPolicyIdentities() {
+
+ String policyIdsResp = createResponse(Arrays.asList(POLICY_1_ID, POLICY_2_ID));
+ whenAsyncPostThenReturn(Mono.just(policyIdsResp));
- Mono<List<String>> returnedMono = clientUnderTest.getPolicyIdentities();
+ List<String> returned = clientUnderTest.getPolicyIdentities().block();
+ assertEquals(2, returned.size(), "");
- verify(asyncRestClientMock).postWithAuthHeader(POLICY_IDENTITIES_URL, inputJsonString, CONTROLLER_USERNAME,
+ AdapterRequest expectedParams = ImmutableAdapterRequest.builder() //
+ .nearRtRicUrl(policiesUrl()) //
+ .build();
+ String expInput = A1ClientHelper.createInputJsonString(expectedParams);
+ verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
CONTROLLER_PASSWORD);
- StepVerifier.create(returnedMono).expectNext(policyIds).expectComplete().verify();
+
}
@Test
@Test
public void testPutPolicyValidResponse() {
- SdncOscAdapterInput inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(RIC_1_URL) //
- .policyTypeId(POLICY_TYPE_1_ID) //
- .policyId(POLICY_1_ID) //
- .policy(POLICY_JSON_VALID) //
+ whenPostReturnOkResponse();
+
+ String returned = clientUnderTest
+ .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
+ .block();
+ assertEquals("OK", returned, "");
+ final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
+ AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
+ .nearRtRicUrl(expUrl) //
+ .body(POLICY_JSON_VALID) //
.build();
- String inputJsonString = A1ClientHelper.createInputJsonString(inputParams);
-
- Mono<String> policyResp = A1ClientHelper.createOutputJsonResponse("returned-policy", POLICY_JSON_VALID);
- whenAsyncPostThenReturn(policyResp);
+ String expInput = A1ClientHelper.createInputJsonString(expectedInputParams);
- Mono<String> 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).expectNext(POLICY_JSON_VALID).expectComplete().verify();
+ verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expInput, CONTROLLER_USERNAME, CONTROLLER_PASSWORD);
}
@Test
- public void testPutPolicyInvalidResponse() {
- SdncOscAdapterInput inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(RIC_1_URL) //
- .policyTypeId(POLICY_TYPE_1_ID) //
- .policyId(POLICY_1_ID) //
- .policy(POLICY_JSON_VALID) //
+ public void testPutPolicyRejected() {
+ final String policyJson = "{}";
+ AdapterResponse adapterResponse = ImmutableAdapterResponse.builder() //
+ .body("NOK") //
+ .httpStatus(400) // ERROR
.build();
- String inputJsonString = A1ClientHelper.createInputJsonString(inputParams);
- Mono<String> policyResp = A1ClientHelper.createOutputJsonResponse("returned-policy", POLICY_JSON_INVALID);
- whenAsyncPostThenReturn(policyResp);
+ String resp = gson().toJson(adapterResponse);
+ whenAsyncPostThenReturn(Mono.just(resp));
Mono<String> returnedMono = clientUnderTest
- .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID));
+ .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, policyJson, POLICY_TYPE_1_ID));
- verify(asyncRestClientMock).postWithAuthHeader(PUT_POLICY_URL, inputJsonString, CONTROLLER_USERNAME,
+ final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
+ AdapterRequest expRequestParams = ImmutableAdapterRequest.builder() //
+ .nearRtRicUrl(expUrl) //
+ .body(policyJson) //
+ .build();
+ String expRequest = A1ClientHelper.createInputJsonString(expRequestParams);
+ verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expRequest, CONTROLLER_USERNAME,
CONTROLLER_PASSWORD);
- StepVerifier.create(returnedMono).expectErrorMatches(throwable -> throwable instanceof JSONException).verify();
+ StepVerifier.create(returnedMono)
+ .expectErrorMatches(throwable -> throwable instanceof WebClientResponseException).verify();
}
@Test
public void testDeletePolicy() {
- SdncOscAdapterInput inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(RIC_1_URL) //
- .policyId(POLICY_1_ID) //
+ whenPostReturnOkResponse();
+
+ String returned = clientUnderTest
+ .deletePolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
+ .block();
+ assertEquals("OK", returned, "");
+ final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
+ AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
+ .nearRtRicUrl(expUrl) //
.build();
- String inputJsonString = A1ClientHelper.createInputJsonString(inputParams);
-
- whenAsyncPostThenReturn(Mono.empty());
-
- Mono<String> returnedMono = clientUnderTest
- .deletePolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID));
+ String expInput = A1ClientHelper.createInputJsonString(expectedInputParams);
- verify(asyncRestClientMock).postWithAuthHeader(DELETE_POLICY_URL, inputJsonString, CONTROLLER_USERNAME,
+ verify(asyncRestClientMock).postWithAuthHeader(DELETE_A1_URL, expInput, CONTROLLER_USERNAME,
CONTROLLER_PASSWORD);
- StepVerifier.create(returnedMono).expectComplete().verify();
- }
-
- @Test
- public void testDeleteAllPolicies() {
- SdncOscAdapterInput inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(RIC_1_URL) //
- .build();
- String inputJsonStringGetIds = A1ClientHelper.createInputJsonString(inputParams);
- inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(RIC_1_URL) //
- .policyId(POLICY_1_ID) //
- .build();
- String inputJsonStringDeletePolicy1 = A1ClientHelper.createInputJsonString(inputParams);
- inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(RIC_1_URL) //
- .policyId(POLICY_2_ID) //
- .build();
- String inputJsonStringDeletePolicy2 = A1ClientHelper.createInputJsonString(inputParams);
-
- List<String> policyIds = Arrays.asList(POLICY_1_ID, POLICY_2_ID);
- Mono<String> policyIdsResp = A1ClientHelper.createOutputJsonResponse("policy-id-list", policyIds.toString());
- whenAsyncPostThenReturn(policyIdsResp).thenReturn(Mono.empty());
-
- Flux<String> returnedFlux = clientUnderTest.deleteAllPolicies();
-
- StepVerifier.create(returnedFlux).expectComplete().verify();
- verify(asyncRestClientMock).postWithAuthHeader(POLICY_IDENTITIES_URL, inputJsonStringGetIds,
- CONTROLLER_USERNAME, CONTROLLER_PASSWORD);
- verify(asyncRestClientMock).postWithAuthHeader(DELETE_POLICY_URL, inputJsonStringDeletePolicy1,
- CONTROLLER_USERNAME, CONTROLLER_PASSWORD);
- verify(asyncRestClientMock).postWithAuthHeader(DELETE_POLICY_URL, inputJsonStringDeletePolicy2,
- CONTROLLER_USERNAME, CONTROLLER_PASSWORD);
}
@Test
public void testGetStatus() {
- SdncOscAdapterInput inputParams = ImmutableSdncOscAdapterInput.builder() //
- .nearRtRicUrl(RIC_1_URL) //
- .policyId(POLICY_1_ID) //
- .build();
- String inputJsonString = A1ClientHelper.createInputJsonString(inputParams);
-
- String status = "STATUS";
- Mono<String> policyStatusResp = A1ClientHelper.createOutputJsonResponse("policy-status", status);
- whenAsyncPostThenReturn(policyStatusResp);
+ whenPostReturnOkResponse();
Policy policy = A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID);
String returnedStatus = clientUnderTest.getPolicyStatus(policy).block();
- assertEquals(status, returnedStatus, "unexpexted status");
+ assertEquals("OK", returnedStatus, "unexpeted status");
- final String expectedUrl = "/A1-ADAPTER-API:getPolicyStatus";
- verify(asyncRestClientMock).postWithAuthHeader(expectedUrl, inputJsonString, CONTROLLER_USERNAME,
+ final String expUrl = policiesUrl() + "/" + POLICY_1_ID + "/status";
+ AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
+ .nearRtRicUrl(expUrl) //
+ .build();
+ String expInput = A1ClientHelper.createInputJsonString(expectedInputParams);
+
+ verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_STATUS_URL, expInput, CONTROLLER_USERNAME,
CONTROLLER_PASSWORD);
}
+ private void whenPostReturnOkResponse() {
+ AdapterResponse adapterResponse = ImmutableAdapterResponse.builder() //
+ .body("OK") //
+ .httpStatus(200) //
+ .build();
+
+ String resp = gson().toJson(adapterResponse);
+ whenAsyncPostThenReturn(Mono.just(resp));
+ }
+
private OngoingStubbing<Mono<String>> whenAsyncPostThenReturn(Mono<String> response) {
return when(asyncRestClientMock.postWithAuthHeader(anyString(), anyString(), anyString(), anyString()))
.thenReturn(response);
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
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.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
+import org.oransc.policyagent.configuration.RicConfig;
import org.oransc.policyagent.repository.Policy;
import reactor.core.publisher.Flux;
@ExtendWith(MockitoExtension.class)
public class StdA1ClientTest {
private static final String RIC_URL = "RicUrl";
- private static final String POLICIES_IDENTITIES_URL = "/policies";
- private static final String POLICIES_URL = "/policies/";
private static final String POLICY_TYPE_1_NAME = "type1";
private static final String POLICY_1_ID = "policy1";
private static final String POLICY_2_ID = "policy2";
- private static final String POLICY_JSON_VALID = "{\"policyId\":\"policy1\"}";
- private static final String POLICY_JSON_INVALID = "\"policyId\":\"policy1\"}";
+ private static final String POLICY_JSON = "{\"policyId\":\"policy1\"}";
private static final String POLICY_TYPE = "typeName";
StdA1ClientVersion1 clientUnderTest;
@Mock
AsyncRestClient asyncRestClientMock;
+ @Mock
+ RicConfig ricConfigMock;
+
@BeforeEach
public void init() {
- clientUnderTest = new StdA1ClientVersion1(asyncRestClientMock);
+ clientUnderTest = new StdA1ClientVersion1(asyncRestClientMock, ricConfigMock);
+ }
+
+ private String policiesUrl() {
+ return RIC_URL + "/A1-P/v1/policies";
+ }
+
+ private String policiesBaseUrl() {
+ return policiesUrl() + "/";
}
@Test
@Test
public void testGetPolicyIdentities() {
+ doReturn(RIC_URL).when(ricConfigMock).baseUrl();
Mono<String> policyIds = Mono.just(Arrays.asList(POLICY_1_ID, POLICY_2_ID).toString());
when(asyncRestClientMock.get(anyString())).thenReturn(policyIds);
List<String> result = clientUnderTest.getPolicyIdentities().block();
assertEquals(2, result.size(), "");
- verify(asyncRestClientMock).get(POLICIES_IDENTITIES_URL);
+ verify(asyncRestClientMock).get(policiesUrl());
}
@Test
@Test
public void testPutPolicyValidResponse() {
- when(asyncRestClientMock.put(anyString(), anyString())).thenReturn(Mono.just(POLICY_JSON_VALID));
-
- Mono<String> policyMono = clientUnderTest
- .putPolicy(A1ClientHelper.createPolicy(RIC_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE));
-
- verify(asyncRestClientMock).put(POLICIES_URL + POLICY_1_ID, POLICY_JSON_VALID);
- StepVerifier.create(policyMono).expectNext(POLICY_JSON_VALID).expectComplete().verify();
- }
-
- @Test
- public void testPutPolicyInvalidResponse() {
- when(asyncRestClientMock.put(anyString(), anyString())).thenReturn(Mono.just(POLICY_JSON_INVALID));
+ doReturn(RIC_URL).when(ricConfigMock).baseUrl();
+ when(asyncRestClientMock.put(anyString(), anyString())).thenReturn(Mono.just(POLICY_JSON));
- Mono<String> policyMono = clientUnderTest
- .putPolicy(A1ClientHelper.createPolicy(RIC_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE));
+ Mono<String> policyMono =
+ clientUnderTest.putPolicy(A1ClientHelper.createPolicy(RIC_URL, POLICY_1_ID, POLICY_JSON, POLICY_TYPE));
- StepVerifier.create(policyMono).expectErrorMatches(throwable -> throwable instanceof JSONException).verify();
+ verify(asyncRestClientMock).put(policiesBaseUrl() + POLICY_1_ID, POLICY_JSON);
+ StepVerifier.create(policyMono).expectNext(POLICY_JSON).expectComplete().verify();
}
@Test
public void testDeletePolicy() {
- when(asyncRestClientMock.delete(POLICIES_URL + POLICY_1_ID)).thenReturn(Mono.empty());
+ doReturn(RIC_URL).when(ricConfigMock).baseUrl();
+ final String url = policiesBaseUrl() + POLICY_1_ID;
+ when(asyncRestClientMock.delete(url)).thenReturn(Mono.empty());
- Policy policy = A1ClientHelper.createPolicy(RIC_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE);
+ Policy policy = A1ClientHelper.createPolicy(RIC_URL, POLICY_1_ID, POLICY_JSON, POLICY_TYPE);
Mono<?> responseMono = clientUnderTest.deletePolicy(policy);
- verify(asyncRestClientMock).delete(POLICIES_URL + POLICY_1_ID);
+ verify(asyncRestClientMock).delete(url);
StepVerifier.create(responseMono).expectComplete().verify();
}
@Test
public void testDeleteAllPolicies() {
+ doReturn(RIC_URL).when(ricConfigMock).baseUrl();
Mono<String> policyIds = Mono.just(Arrays.asList(POLICY_1_ID, POLICY_2_ID).toString());
- when(asyncRestClientMock.get(POLICIES_IDENTITIES_URL)).thenReturn(policyIds);
+ when(asyncRestClientMock.get(policiesUrl())).thenReturn(policyIds);
when(asyncRestClientMock.delete(anyString())).thenReturn(Mono.empty());
Flux<String> responseFlux = clientUnderTest.deleteAllPolicies();
StepVerifier.create(responseFlux).expectComplete().verify();
- verify(asyncRestClientMock).get(POLICIES_IDENTITIES_URL);
- verify(asyncRestClientMock).delete(POLICIES_URL + POLICY_1_ID);
- verify(asyncRestClientMock).delete(POLICIES_URL + POLICY_2_ID);
+ verify(asyncRestClientMock).get(policiesUrl());
+ verify(asyncRestClientMock).delete(policiesBaseUrl() + POLICY_1_ID);
+ verify(asyncRestClientMock).delete(policiesBaseUrl() + POLICY_2_ID);
}
}
public void whenCorrectDmaapConfig() throws Exception {
JsonObject jsonRootObject = getJsonRootObject();
- parserUnderTest.parse(jsonRootObject);
+ ApplicationConfigParser.ConfigParserResult result = parserUnderTest.parse(jsonRootObject);
- Properties actualPublisherConfig = parserUnderTest.getDmaapPublisherConfig();
+ Properties actualPublisherConfig = result.dmaapPublisherConfig();
assertAll("publisherConfig",
() -> assertEquals("localhost:6845/events", actualPublisherConfig.get("ServiceName"), "Wrong ServiceName"),
() -> assertEquals("A1-POLICY-AGENT-WRITE", actualPublisherConfig.get("topic"), "Wrong topic"),
() -> assertEquals(15000, actualPublisherConfig.get("timeout"), "Wrong timeout"),
() -> assertEquals(100, actualPublisherConfig.get("limit"), "Wrong limit"));
- Properties actualConsumerConfig = parserUnderTest.getDmaapConsumerConfig();
+ Properties actualConsumerConfig = result.dmaapConsumerConfig();
assertAll("consumerConfig",
() -> assertEquals("localhost:6845/events", actualConsumerConfig.get("ServiceName"), "Wrong ServiceName"),
() -> assertEquals("A1-POLICY-AGENT-READ", actualConsumerConfig.get("topic"), "Wrong topic"),
"A1 adapter";\r
}\r
\r
- // Get an array of integer policy type ids\r
- // Each item in the returned array will be regarded as one policy-type-id.\r
- rpc getPolicyTypeIdentities {\r
+ rpc putA1Policy {\r
input {\r
leaf near-rt-ric-url {\r
+ type inet:uri;\r
+ }\r
+ leaf body {\r
type string;\r
}\r
}\r
-\r
output {\r
- leaf-list policy-type-id-list {\r
+ leaf body {\r
type string;\r
}\r
+ leaf http-status {\r
+ type int32;\r
+ }\r
}\r
}\r
\r
- // Get an array of integer policy ids\r
- // Each item in the returned array will be regarded as one policy-id.\r
- rpc getPolicyIdentities {\r
+ rpc getA1Policy {\r
input {\r
leaf near-rt-ric-url {\r
- type string;\r
+ type inet:uri;\r
}\r
}\r
-\r
output {\r
- leaf-list policy-id-list {\r
+ leaf body {\r
type string;\r
}\r
+ leaf http-status {\r
+ type int32;\r
+ }\r
}\r
}\r
\r
- // Get a policy type\r
- rpc getPolicyType {\r
+ rpc getA1PolicyStatus {\r
input {\r
leaf near-rt-ric-url {\r
- type string;\r
- }\r
- leaf policy-type-id {\r
- type string;\r
+ type inet:uri;\r
}\r
}\r
output {\r
- leaf policy-type {\r
+ leaf body {\r
type string;\r
}\r
+ leaf http-status {\r
+ type int32;\r
+ }\r
}\r
}\r
\r
- // Create a policy\r
- rpc putPolicy {\r
+ rpc getA1PolicyType {\r
input {\r
leaf near-rt-ric-url {\r
- type string;\r
- }\r
- leaf policy-id {\r
- type string;\r
- }\r
- leaf policy-type-id {\r
- type string;\r
- }\r
- leaf policy {\r
- type string;\r
+ type inet:uri;\r
}\r
}\r
output {\r
- leaf returned-policy {\r
- type string;\r
- }\r
- }\r
- }\r
-\r
- // Delete a policy\r
- rpc deletePolicy {\r
- input {\r
- leaf near-rt-ric-url {\r
+ leaf body {\r
type string;\r
}\r
- leaf policy-id {\r
- type string;\r
+ leaf http-status {\r
+ type int32;\r
}\r
}\r
}\r
\r
- // Get a policy status\r
- rpc getPolicyStatus {\r
+ rpc deleteA1Policy {\r
input {\r
leaf near-rt-ric-url {\r
- type string;\r
- }\r
- leaf policy-id {\r
- type string;\r
+ type inet:uri;\r
}\r
}\r
output {\r
- leaf policy-status {\r
+ leaf body {\r
type string;\r
}\r
+ leaf http-status {\r
+ type int32;\r
+ }\r
}\r
}\r
}
\ No newline at end of file
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import org.onap.sdnc.northbound.restadapter.NearRicUrlProvider;
import org.onap.sdnc.northbound.restadapter.RestAdapter;
import org.onap.sdnc.northbound.restadapter.RestAdapterImpl;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.A1ADAPTERAPIService;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.DeletePolicyInput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.DeletePolicyOutput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.DeletePolicyOutputBuilder;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyIdentitiesInput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyIdentitiesOutput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyIdentitiesOutputBuilder;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyStatusInput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyStatusOutput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyStatusOutputBuilder;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyTypeIdentitiesInput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyTypeIdentitiesOutput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyTypeIdentitiesOutputBuilder;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyTypeInput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyTypeOutput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyTypeOutputBuilder;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.PutPolicyInput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.PutPolicyOutput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.PutPolicyOutputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.DeleteA1PolicyInput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.DeleteA1PolicyOutput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.DeleteA1PolicyOutputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyInput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyInputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyOutput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyOutputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyStatusInput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyStatusOutput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyStatusOutputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyTypeInput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyTypeOutput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyTypeOutputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.PutA1PolicyInput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.PutA1PolicyOutput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.PutA1PolicyOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.slf4j.Logger;
protected RpcProviderRegistry rpcRegistry;
protected BindingAwareBroker.RpcRegistration<?> rpcRegistration;
private RestAdapter restAdapter;
- private NearRicUrlProvider nearRicUrlProvider;
public NonrtRicApiProvider(DataBroker dataBroker, NotificationPublishService notificationPublishService,
RpcProviderRegistry rpcProviderRegistry) {
log.info("Initializing provider for {}", APP_NAME);
createContainers();
restAdapter = new RestAdapterImpl();
- nearRicUrlProvider = new NearRicUrlProvider();
log.info("Initialization complete for {}", APP_NAME);
}
}
@Override
- public ListenableFuture<RpcResult<GetPolicyTypeIdentitiesOutput>> getPolicyTypeIdentities(
- GetPolicyTypeIdentitiesInput input) {
- log.info("Start of getPolicyTypeIdentities");
- GetPolicyTypeIdentitiesOutputBuilder responseBuilder = new GetPolicyTypeIdentitiesOutputBuilder();
- String uri = nearRicUrlProvider.policyTypesUrl(String.valueOf(input.getNearRtRicUrl()));
- ResponseEntity<List<String>> response = restAdapter.get(uri, List.class);
+ public ListenableFuture<RpcResult<PutA1PolicyOutput>> putA1Policy(PutA1PolicyInput input) {
+ log.info("Start of putPolicy");
+ final Uri uri = input.getNearRtRicUrl();
+
+ log.info("PUT Request input.GetA1Policy() : {} ", uri);
+ ResponseEntity<String> response = restAdapter.put(uri.getValue(), input.getBody(), String.class);
+ PutA1PolicyOutputBuilder responseBuilder = new PutA1PolicyOutputBuilder();
if (response.hasBody()) {
- log.info("Response getPolicyTypeIdentities : {} ", response.getBody());
- responseBuilder.setPolicyTypeIdList(response.getBody());
+ log.info("Response PutA1Policy : {} ", response.getBody());
+ responseBuilder.setBody(response.getBody());
}
- log.info("End of getPolicyTypeIdentities");
- RpcResult<GetPolicyTypeIdentitiesOutput> rpcResult = RpcResultBuilder.<GetPolicyTypeIdentitiesOutput>status(true)
+ responseBuilder.setHttpStatus(response.getStatusCodeValue());
+ log.info("End of PutA1Policy");
+ RpcResult<PutA1PolicyOutput> rpcResult = RpcResultBuilder.<PutA1PolicyOutput>status(true)
.withResult(responseBuilder.build()).build();
return Futures.immediateFuture(rpcResult);
}
@Override
- public ListenableFuture<RpcResult<GetPolicyIdentitiesOutput>> getPolicyIdentities(GetPolicyIdentitiesInput input) {
- log.info("Start of getPolicyIdentities");
- GetPolicyIdentitiesOutputBuilder responseBuilder = new GetPolicyIdentitiesOutputBuilder();
- String uri = nearRicUrlProvider.policiesUrl(String.valueOf(input.getNearRtRicUrl()));
- ResponseEntity<List<String>> response = restAdapter.get(uri, List.class);
+ public ListenableFuture<RpcResult<DeleteA1PolicyOutput>> deleteA1Policy(DeleteA1PolicyInput input) {
+ log.info("Start of DeleteA1Policy");
+ final Uri uri = input.getNearRtRicUrl();
+ ResponseEntity<Object> response = restAdapter.delete(uri.getValue());
+ log.info("End of DeleteA1Policy");
+ DeleteA1PolicyOutputBuilder responseBuilder = new DeleteA1PolicyOutputBuilder();
if (response.hasBody()) {
- log.info("Response getPolicyIdentities : {} ", response.getBody());
- responseBuilder.setPolicyIdList(response.getBody());
+ log.info("Response PutA1Policy : {} ", response.getBody());
+ responseBuilder.setBody(response.getBody().toString());
}
- log.info("End of getPolicyIdentities");
- RpcResult<GetPolicyIdentitiesOutput> rpcResult = RpcResultBuilder.<GetPolicyIdentitiesOutput>status(true)
+ responseBuilder.setHttpStatus(response.getStatusCodeValue());
+ RpcResult<DeleteA1PolicyOutput> rpcResult = RpcResultBuilder.<DeleteA1PolicyOutput>status(true)
.withResult(responseBuilder.build()).build();
return Futures.immediateFuture(rpcResult);
}
- @Override
- public ListenableFuture<RpcResult<GetPolicyTypeOutput>> getPolicyType(GetPolicyTypeInput input) {
- log.info("Start of getPolicyType; Policy Type Id : {} ", input.getPolicyTypeId());
- GetPolicyTypeOutputBuilder responseBuilder = new GetPolicyTypeOutputBuilder();
- String uri = nearRicUrlProvider.getPolicyTypeUrl(String.valueOf(input.getNearRtRicUrl()),
- String.valueOf(input.getPolicyTypeId()));
- ResponseEntity<String> response = restAdapter.get(uri, String.class);
+ private GetA1PolicyOutput getA1(GetA1PolicyInput input) {
+ log.info("Start of getA1");
+ final Uri uri = input.getNearRtRicUrl();
+ ResponseEntity<String> response = restAdapter.get(uri.getValue(), String.class);
+ log.info("End of getA1");
+ GetA1PolicyOutputBuilder responseBuilder = new GetA1PolicyOutputBuilder();
if (response.hasBody()) {
- log.info("Response getPolicyType : {} ", response.getBody());
- responseBuilder.setPolicyType(response.getBody());
+ log.info("Response getA1 : {} ", response.getBody());
+ responseBuilder.setBody(response.getBody());
}
- log.info("End of getPolicyType");
- RpcResult<GetPolicyTypeOutput> rpcResult = RpcResultBuilder.<GetPolicyTypeOutput>status(true)
- .withResult(responseBuilder.build()).build();
- return Futures.immediateFuture(rpcResult);
+ responseBuilder.setHttpStatus(response.getStatusCodeValue());
+ return responseBuilder.build();
}
@Override
- public ListenableFuture<RpcResult<PutPolicyOutput>> putPolicy(PutPolicyInput input) {
- log.info("Start of putPolicy");
- PutPolicyOutputBuilder responseBuilder = new PutPolicyOutputBuilder();
- String uri = nearRicUrlProvider.putPolicyUrl(String.valueOf(input.getNearRtRicUrl()),
- String.valueOf(input.getPolicyId()), String.valueOf(input.getPolicyTypeId()));
- log.info("PUT Request input.getPolicy() : {} ", input.getPolicy());
- ResponseEntity<String> response = restAdapter.put(uri, input.getPolicy(), String.class);
- if (response.hasBody()) {
- log.info("Response putPolicy : {} ", response.getBody());
- responseBuilder.setReturnedPolicy(response.getBody());
- }
- log.info("End of putPolicy");
- RpcResult<PutPolicyOutput> rpcResult = RpcResultBuilder.<PutPolicyOutput>status(true)
- .withResult(responseBuilder.build()).build();
+ public ListenableFuture<RpcResult<GetA1PolicyOutput>> getA1Policy(GetA1PolicyInput input) {
+ GetA1PolicyOutput output = getA1(input);
+ RpcResult<GetA1PolicyOutput> rpcResult = RpcResultBuilder.<GetA1PolicyOutput>status(true).withResult(output)
+ .build();
return Futures.immediateFuture(rpcResult);
}
@Override
- public ListenableFuture<RpcResult<DeletePolicyOutput>> deletePolicy(DeletePolicyInput input) {
- log.info("Start of deletePolicy");
- DeletePolicyOutputBuilder responseBuilder = new DeletePolicyOutputBuilder();
- String uri = nearRicUrlProvider.deletePolicyUrl(String.valueOf(input.getNearRtRicUrl()),
- String.valueOf(input.getPolicyId()));
- restAdapter.delete(uri);
- log.info("End of deletePolicy");
- RpcResult<DeletePolicyOutput> rpcResult = RpcResultBuilder.<DeletePolicyOutput>status(true)
- .withResult(responseBuilder.build()).build();
- return Futures.immediateFuture(rpcResult);
+ public ListenableFuture<RpcResult<GetA1PolicyStatusOutput>> getA1PolicyStatus(GetA1PolicyStatusInput input) {
+ GetA1PolicyInputBuilder getInputBuilder = new GetA1PolicyInputBuilder();
+ getInputBuilder.setNearRtRicUrl(input.getNearRtRicUrl());
+ GetA1PolicyOutput getOutput = getA1(getInputBuilder.build());
+
+ GetA1PolicyStatusOutputBuilder outputBuilder = new GetA1PolicyStatusOutputBuilder();
+ outputBuilder.setBody(getOutput.getBody());
+ outputBuilder.setHttpStatus(getOutput.getHttpStatus());
+
+ return Futures.immediateFuture(RpcResultBuilder.<GetA1PolicyStatusOutput>status(true) //
+ .withResult(outputBuilder.build()) //
+ .build());
}
@Override
- public ListenableFuture<RpcResult<GetPolicyStatusOutput>> getPolicyStatus(GetPolicyStatusInput input) {
- log.debug("Policy Id : {} ", input.getPolicyId());
- GetPolicyStatusOutputBuilder responseBuilder = new GetPolicyStatusOutputBuilder();
- String uri = nearRicUrlProvider.getPolicyStatusUrl(input.getNearRtRicUrl(), input.getPolicyId());
- ResponseEntity<String> response = restAdapter.get(uri, String.class);
- if (response.hasBody()) {
- log.info("Response getPolicyStatus : {} ", response.getBody());
- responseBuilder.setPolicyStatus(response.getBody());
- }
- RpcResult<GetPolicyStatusOutput> rpcResult = RpcResultBuilder.<GetPolicyStatusOutput>status(true)
- .withResult(responseBuilder.build()).build();
- return Futures.immediateFuture(rpcResult);
+ public ListenableFuture<RpcResult<GetA1PolicyTypeOutput>> getA1PolicyType(GetA1PolicyTypeInput input) {
+ GetA1PolicyInputBuilder getInputBuilder = new GetA1PolicyInputBuilder();
+ getInputBuilder.setNearRtRicUrl(input.getNearRtRicUrl());
+ GetA1PolicyOutput getOutput = getA1(getInputBuilder.build());
+
+ GetA1PolicyTypeOutputBuilder outputBuilder = new GetA1PolicyTypeOutputBuilder();
+ outputBuilder.setBody(getOutput.getBody());
+ outputBuilder.setHttpStatus(getOutput.getHttpStatus());
+
+ return Futures.immediateFuture(RpcResultBuilder.<GetA1PolicyTypeOutput>status(true) //
+ .withResult(outputBuilder.build()) //
+ .build());
}
+
}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2020 Nordix Foundation.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.sdnc.northbound.restadapter;
-
-import org.springframework.web.util.UriComponentsBuilder;
-
-/**
- * This class provides Near-RIC api to invoke the A1 interface
- *
- * @author lathishbabu.ganesan@est.tech
- *
- */
-
-public class NearRicUrlProvider {
-
- /**
- * Retrieve the base url of the Near-RIC
- *
- * @param nearRtRicUrl the near-rt-ric url
- * @return the base url
- */
- public String getBaseUrl(final String nearRtRicUrl) {
- return nearRtRicUrl + "/A1-P/v1";
- }
-
- /**
- * Retrieve the policytypes url
- *
- * @param nearRtRicUrl the near-rt-ric url
- * @return the policytypes url
- */
- public String policyTypesUrl(final String nearRtRicUrl) {
- return UriComponentsBuilder.fromUriString(getBaseUrl(nearRtRicUrl)).pathSegment("policytypes").build().toString();
- }
-
- /**
- * Retrieve the policies url
- *
- * @param nearRtRicUrl the near-rt-ric url
- * @return the policies url
- */
- public String policiesUrl(final String nearRtRicUrl) {
- return getBaseUrl(nearRtRicUrl) + "/policies";
- }
-
- /**
- * Retrieve the url of policy type
- *
- * @param nearRtRicUrl the near-rt-ric url
- * @param policyTypeId Policy Type Id
- * @return the policy type url
- */
- public String getPolicyTypeUrl(final String nearRtRicUrl, final String policyTypeId) {
- return UriComponentsBuilder.fromUriString(policyTypesUrl(nearRtRicUrl)).pathSegment(policyTypeId).build()
- .toString();
- }
-
- /**
- * Retrieve the url of putPolicy
- *
- * @param nearRtRicUrl the near-rt-ric url
- * @param policyId Policy Id
- * @param policyTypeId Policy Type Id
- * @return the putPolicy url
- */
- public String putPolicyUrl(final String nearRtRicUrl, final String policyId, final String policyTypeId) {
- UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(policiesUrl(nearRtRicUrl)).pathSegment(policyId);
-
- if (!policyTypeId.isEmpty()) {
- builder.queryParam("policyTypeId", policyTypeId);
- }
- return builder.build().toString();
- }
-
- /**
- * Retrieve the url of deletePolicy
- *
- * @param nearRtRicUrl the near-rt-ric url
- * @param policyId Policy Id
- * @return the deletePolicy url
- */
- public String deletePolicyUrl(final String nearRtRicUrl, final String policyId) {
- return UriComponentsBuilder.fromUriString(policiesUrl(nearRtRicUrl)).pathSegment(policyId).build().toString();
- }
-
- public String getPolicyStatusUrl(String nearRtRicUrl, String policyId) {
- return policiesUrl(nearRtRicUrl) + "/" + policyId + "/status";
- }
-}
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.util.ArrayList;
-import java.util.List;
+
import java.util.concurrent.ExecutionException;
+
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import org.onap.sdnc.northbound.provider.NonrtRicApiProvider;
-import org.onap.sdnc.northbound.restadapter.NearRicUrlProvider;
import org.onap.sdnc.northbound.restadapter.RestAdapter;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
import org.opendaylight.controller.md.sal.binding.test.AbstractConcurrentDataBrokerTest;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyIdentitiesInputBuilder;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyIdentitiesOutput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyStatusInputBuilder;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyStatusOutput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyTypeIdentitiesInputBuilder;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyTypeIdentitiesOutput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyTypeInputBuilder;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetPolicyTypeOutput;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.PutPolicyInputBuilder;
-import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.PutPolicyOutput;
-import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.DeleteA1PolicyInputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.DeleteA1PolicyOutput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyInputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyOutput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyStatusInputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyStatusOutput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyTypeInputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.GetA1PolicyTypeOutput;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.PutA1PolicyInputBuilder;
+import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.a1.adapter.rev200122.PutA1PolicyOutput;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
protected RpcProviderRegistry mockRpcProviderRegistry;
@Mock
private RestAdapter restAdapter;
- private NearRicUrlProvider nearRicUrlProvider;
- private static String nearRtRicUrl = "http://ric1:8085";
- private static String policyTypeId = "STD_QoSNudging_0.1.0";
- private static String policyId = "3d2157af-6a8f-4a7c-810f-38c2f824bf12";
+ private static Uri nearRtRicUrl = new Uri("http://ric1:8085");
@Before
public void setUp() throws Exception {
- nearRicUrlProvider = new NearRicUrlProvider();
dataBroker = getDataBroker();
nonrtRicApiProvider = new NonrtRicApiProvider(dataBroker, mockNotificationPublishService, mockRpcProviderRegistry);
}
@Test
- public void testGetPolicyTypeIdentities() throws InterruptedException, ExecutionException {
- GetPolicyTypeIdentitiesInputBuilder inputBuilder = new GetPolicyTypeIdentitiesInputBuilder();
+ public void testGetA1Policy() throws InterruptedException, ExecutionException {
+ GetA1PolicyInputBuilder inputBuilder = new GetA1PolicyInputBuilder();
inputBuilder.setNearRtRicUrl(nearRtRicUrl);
Whitebox.setInternalState(nonrtRicApiProvider, "restAdapter", restAdapter);
- String uri = nearRicUrlProvider.policyTypesUrl(inputBuilder.build().getNearRtRicUrl());
- List<String> policyTypeIdentities = new ArrayList<>();
- policyTypeIdentities.add(policyTypeId);
- ResponseEntity<Object> getPolicyTypeIdentitiesResponse = new ResponseEntity<>(policyTypeIdentities, HttpStatus.OK);
- when(restAdapter.get(eq(uri), eq(List.class))).thenReturn(getPolicyTypeIdentitiesResponse);
- ListenableFuture<RpcResult<GetPolicyTypeIdentitiesOutput>> result = nonrtRicApiProvider
- .getPolicyTypeIdentities(inputBuilder.build());
- Assert.assertEquals(policyTypeIdentities, result.get().getResult().getPolicyTypeIdList());
+ String returnedBody = "returned body";
+ ResponseEntity<Object> getResponse = new ResponseEntity<>(returnedBody, HttpStatus.OK);
+ when(restAdapter.get(eq(nearRtRicUrl.getValue()), eq(String.class))).thenReturn(getResponse);
+ GetA1PolicyOutput result = nonrtRicApiProvider.getA1Policy(inputBuilder.build()).get().getResult();
+ Assert.assertEquals(returnedBody, result.getBody());
+ Assert.assertTrue(HttpStatus.OK.value() == result.getHttpStatus());
}
@Test
- public void testGetPolicyIdentities() throws InterruptedException, ExecutionException {
- GetPolicyIdentitiesInputBuilder inputBuilder = new GetPolicyIdentitiesInputBuilder();
+ public void testGetA1PolicyType() throws InterruptedException, ExecutionException {
+ GetA1PolicyTypeInputBuilder inputBuilder = new GetA1PolicyTypeInputBuilder();
inputBuilder.setNearRtRicUrl(nearRtRicUrl);
Whitebox.setInternalState(nonrtRicApiProvider, "restAdapter", restAdapter);
- String uri = nearRicUrlProvider.policiesUrl(inputBuilder.build().getNearRtRicUrl());
- List<String> policyIdentities = new ArrayList<>();
- policyIdentities.add(policyId);
- ResponseEntity<Object> getPolicyIdentitiesResponse = new ResponseEntity<>(policyIdentities, HttpStatus.OK);
- when(restAdapter.get(eq(uri), eq(List.class))).thenReturn(getPolicyIdentitiesResponse);
- ListenableFuture<RpcResult<GetPolicyIdentitiesOutput>> result = nonrtRicApiProvider
- .getPolicyIdentities(inputBuilder.build());
- Assert.assertEquals(policyIdentities, result.get().getResult().getPolicyIdList());
+ String returnedBody = "returned body";
+ ResponseEntity<Object> getResponse = new ResponseEntity<>(returnedBody, HttpStatus.OK);
+ when(restAdapter.get(eq(nearRtRicUrl.getValue()), eq(String.class))).thenReturn(getResponse);
+ GetA1PolicyTypeOutput result = nonrtRicApiProvider.getA1PolicyType(inputBuilder.build()).get().getResult();
+ Assert.assertEquals(returnedBody, result.getBody());
+ Assert.assertTrue(HttpStatus.OK.value() == result.getHttpStatus());
}
@Test
- public void testGetPolicyType() throws InterruptedException, ExecutionException {
- GetPolicyTypeInputBuilder inputBuilder = new GetPolicyTypeInputBuilder();
+ public void testGetA1PolicyStatus() throws InterruptedException, ExecutionException {
+ GetA1PolicyStatusInputBuilder inputBuilder = new GetA1PolicyStatusInputBuilder();
inputBuilder.setNearRtRicUrl(nearRtRicUrl);
- inputBuilder.setPolicyTypeId(policyTypeId);
Whitebox.setInternalState(nonrtRicApiProvider, "restAdapter", restAdapter);
- String uri = nearRicUrlProvider.getPolicyTypeUrl(inputBuilder.build().getNearRtRicUrl(),
- String.valueOf(inputBuilder.build().getPolicyTypeId()));
- String testPolicyType = "{}";
- ResponseEntity<Object> getPolicyTypeResponse = new ResponseEntity<>(testPolicyType, HttpStatus.OK);
- when(restAdapter.get(eq(uri), eq(String.class))).thenReturn(getPolicyTypeResponse);
- ListenableFuture<RpcResult<GetPolicyTypeOutput>> result = nonrtRicApiProvider.getPolicyType(inputBuilder.build());
- Assert.assertEquals(testPolicyType, result.get().getResult().getPolicyType());
+ String returnedBody = "returned body";
+ ResponseEntity<Object> getResponse = new ResponseEntity<>(returnedBody, HttpStatus.OK);
+ when(restAdapter.get(eq(nearRtRicUrl.getValue()), eq(String.class))).thenReturn(getResponse);
+ GetA1PolicyStatusOutput result = nonrtRicApiProvider.getA1PolicyStatus(inputBuilder.build()).get().getResult();
+ Assert.assertEquals(returnedBody, result.getBody());
+ Assert.assertTrue(HttpStatus.OK.value() == result.getHttpStatus());
}
@Test
- public void testPutPolicy() throws InterruptedException, ExecutionException {
- PutPolicyInputBuilder inputBuilder = new PutPolicyInputBuilder();
+ public void testPutA1Policy() throws InterruptedException, ExecutionException {
+ PutA1PolicyInputBuilder inputBuilder = new PutA1PolicyInputBuilder();
String testPolicy = "{}";
inputBuilder.setNearRtRicUrl(nearRtRicUrl);
- inputBuilder.setPolicyId(policyId);
- inputBuilder.setPolicyTypeId(policyTypeId);
- inputBuilder.setPolicy(testPolicy);
+ inputBuilder.setBody(testPolicy);
Whitebox.setInternalState(nonrtRicApiProvider, "restAdapter", restAdapter);
- String uri = nearRicUrlProvider.putPolicyUrl(inputBuilder.build().getNearRtRicUrl(), inputBuilder.getPolicyId(),
- inputBuilder.getPolicyTypeId());
- ResponseEntity<String> putPolicyResponse = new ResponseEntity<>(testPolicy, HttpStatus.CREATED);
- when(restAdapter.put(eq(uri), eq(testPolicy), eq(String.class))).thenReturn(putPolicyResponse);
- ListenableFuture<RpcResult<PutPolicyOutput>> result = nonrtRicApiProvider.putPolicy(inputBuilder.build());
- Assert.assertEquals(testPolicy, result.get().getResult().getReturnedPolicy());
+ String returnedBody = "returned body";
+ ResponseEntity<String> putResponse = new ResponseEntity<>(returnedBody, HttpStatus.CREATED);
+ when(restAdapter.put(eq(nearRtRicUrl.getValue()), eq(testPolicy), eq(String.class))).thenReturn(putResponse);
+ PutA1PolicyOutput result = nonrtRicApiProvider.putA1Policy(inputBuilder.build()).get().getResult();
+ Assert.assertEquals(returnedBody, result.getBody());
+ Assert.assertTrue(HttpStatus.CREATED.value() == result.getHttpStatus());
}
@Test
- public void testGetPolicyStatus() throws InterruptedException, ExecutionException {
- GetPolicyStatusInputBuilder inputBuilder = new GetPolicyStatusInputBuilder();
+ public void testDeleteA1() throws InterruptedException, ExecutionException {
+ DeleteA1PolicyInputBuilder inputBuilder = new DeleteA1PolicyInputBuilder();
inputBuilder.setNearRtRicUrl(nearRtRicUrl);
- inputBuilder.setPolicyId(policyId);
Whitebox.setInternalState(nonrtRicApiProvider, "restAdapter", restAdapter);
- String uri = nearRicUrlProvider.getPolicyStatusUrl(nearRtRicUrl, policyId);
- String testPolicyStatus = "STATUS";
- ResponseEntity<Object> getPolicyStatusResponse = new ResponseEntity<>(testPolicyStatus, HttpStatus.OK);
- when(restAdapter.get(eq(uri), eq(String.class))).thenReturn(getPolicyStatusResponse);
- ListenableFuture<RpcResult<GetPolicyStatusOutput>> result = nonrtRicApiProvider
- .getPolicyStatus(inputBuilder.build());
- Assert.assertEquals(testPolicyStatus, result.get().getResult().getPolicyStatus());
+
+ ResponseEntity<Object> getResponse = new ResponseEntity<>(HttpStatus.NO_CONTENT);
+ when(restAdapter.delete(nearRtRicUrl.getValue())).thenReturn(getResponse);
+ DeleteA1PolicyOutput result = nonrtRicApiProvider.deleteA1Policy(inputBuilder.build()).get().getResult();
+ Assert.assertTrue(HttpStatus.NO_CONTENT.value() == result.getHttpStatus());
}
}