0efe14d9f9db5f5d9bf533f279eeb0cbff8646c5
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / clients / OscA1Client.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.oransc.policyagent.clients;
22
23 import java.lang.invoke.MethodHandles;
24 import java.util.ArrayList;
25 import java.util.List;
26 import org.json.JSONArray;
27 import org.json.JSONException;
28 import org.json.JSONObject;
29 import org.oransc.policyagent.configuration.RicConfig;
30 import org.oransc.policyagent.repository.Policy;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.springframework.web.util.UriComponentsBuilder;
34 import reactor.core.publisher.Flux;
35 import reactor.core.publisher.Mono;
36
37 public class OscA1Client implements A1Client {
38     private static final String URL_PREFIX = "/a1-p";
39
40     private static final String POLICY_TYPES = "/policytypes";
41     private static final String CREATE_SCHEMA = "create_schema";
42     private static final String TITLE = "title";
43
44     private static final String HEALTHCHECK = "/healthcheck";
45
46     private static final UriComponentsBuilder POLICY_TYPE_SCHEMA_URI =
47         UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}");
48
49     private static final UriComponentsBuilder POLICY_URI =
50         UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}/policies/{policy-id}");
51
52     private static final UriComponentsBuilder POLICY_IDS_URI =
53         UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}/policies");
54
55     private static final UriComponentsBuilder POLICY_STATUS_URI =
56         UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}/policies/{policy-id}/status");
57
58     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
59
60     private final AsyncRestClient restClient;
61
62     public OscA1Client(RicConfig ricConfig) {
63         String baseUrl = ricConfig.baseUrl() + URL_PREFIX;
64         this.restClient = new AsyncRestClient(baseUrl);
65         if (logger.isDebugEnabled()) {
66             logger.debug("OscA1Client for ric: {}", ricConfig.name());
67         }
68     }
69
70     public OscA1Client(AsyncRestClient restClient) {
71         this.restClient = restClient;
72     }
73
74     @Override
75     public Mono<List<String>> getPolicyTypeIdentities() {
76         return getPolicyTypeIds() //
77             .collectList();
78     }
79
80     @Override
81     public Mono<List<String>> getPolicyIdentities() {
82         return getPolicyTypeIds() //
83             .flatMap(this::getPolicyIdentitiesByType) //
84             .collectList();
85     }
86
87     @Override
88     public Mono<String> getPolicyTypeSchema(String policyTypeId) {
89         String uri = POLICY_TYPE_SCHEMA_URI.buildAndExpand(policyTypeId).toUriString();
90         return restClient.get(uri) //
91             .flatMap(response -> getCreateSchema(response, policyTypeId));
92     }
93
94     @Override
95     public Mono<String> putPolicy(Policy policy) {
96         String uri = POLICY_URI.buildAndExpand(policy.type().name(), policy.id()).toUriString();
97         return restClient.put(uri, policy.json());
98     }
99
100     @Override
101     public Mono<String> deletePolicy(Policy policy) {
102         return deletePolicyById(policy.type().name(), policy.id());
103     }
104
105     @Override
106     public Mono<A1ProtocolType> getProtocolVersion() {
107         return restClient.get(HEALTHCHECK) //
108             .flatMap(notUsed -> Mono.just(A1ProtocolType.OSC_V1));
109     }
110
111     @Override
112     public Flux<String> deleteAllPolicies() {
113         return getPolicyTypeIds() //
114             .flatMap(this::deletePoliciesForType);
115     }
116
117     @Override
118     public Mono<String> getPolicyStatus(Policy policy) {
119         String uri = POLICY_STATUS_URI.buildAndExpand(policy.type().name(), policy.id()).toUriString();
120         return restClient.get(uri);
121
122     }
123
124     private Flux<String> getPolicyTypeIds() {
125         return restClient.get(POLICY_TYPES) //
126             .flatMapMany(this::parseJsonArrayOfString);
127     }
128
129     private Flux<String> getPolicyIdentitiesByType(String typeId) {
130         return restClient.get(POLICY_IDS_URI.buildAndExpand(typeId).toUriString()) //
131             .flatMapMany(this::parseJsonArrayOfString);
132     }
133
134     private Mono<String> getCreateSchema(String policyTypeResponse, String policyTypeId) {
135         try {
136             JSONObject obj = new JSONObject(policyTypeResponse);
137             JSONObject schemaObj = obj.getJSONObject(CREATE_SCHEMA);
138             schemaObj.put(TITLE, policyTypeId);
139             return Mono.just(schemaObj.toString());
140         } catch (Exception e) {
141             logger.error("Unexcpected response for policy type: {}", policyTypeResponse, e);
142             return Mono.error(e);
143         }
144     }
145
146     private Mono<String> deletePolicyById(String typeId, String policyId) {
147         String uri = POLICY_URI.buildAndExpand(typeId, policyId).toUriString();
148         return restClient.delete(uri);
149     }
150
151     private Flux<String> deletePoliciesForType(String typeId) {
152         return getPolicyIdentitiesByType(typeId) //
153             .flatMap(policyId -> deletePolicyById(typeId, policyId));
154     }
155
156     private Flux<String> parseJsonArrayOfString(String inputString) {
157         try {
158             List<String> arrayList = new ArrayList<>();
159             JSONArray jsonArray = new JSONArray(inputString);
160             for (int i = 0; i < jsonArray.length(); i++) {
161                 arrayList.add(jsonArray.getString(i));
162             }
163             logger.debug("A1 client: received list = {}", arrayList);
164             return Flux.fromIterable(arrayList);
165         } catch (JSONException ex) { // invalid json
166             return Flux.error(ex);
167         }
168     }
169 }