Remove code smells from policyagent/clients
[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
27 import org.json.JSONArray;
28 import org.json.JSONException;
29 import org.json.JSONObject;
30 import org.oransc.policyagent.configuration.RicConfig;
31 import org.oransc.policyagent.repository.Policy;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.web.util.UriComponentsBuilder;
35 import reactor.core.publisher.Flux;
36 import reactor.core.publisher.Mono;
37
38 public class OscA1Client implements A1Client {
39     private static final String URL_PREFIX = "/a1-p";
40
41     private static final String POLICYTYPES = "/policytypes";
42     private static final String CREATE_SCHEMA = "create_schema";
43     private static final String TITLE = "title";
44
45     private static final String HEALTHCHECK = "/healthcheck";
46
47     private static final UriComponentsBuilder POLICY_TYPE_SCHEMA_URI =
48         UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}");
49
50     private static final UriComponentsBuilder POLICY_URI =
51         UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}/policies/{policy-id}");
52
53     private static final UriComponentsBuilder POLICY_IDS_URI =
54         UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}/policies");
55
56     private static final UriComponentsBuilder POLICY_STATUS_URI =
57         UriComponentsBuilder.fromPath("/policytypes/{policy-type-name}/policies/{policy-id}/status");
58
59     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
60
61     private final AsyncRestClient restClient;
62
63     public OscA1Client(RicConfig ricConfig) {
64         String baseUrl = ricConfig.baseUrl() + URL_PREFIX;
65         this.restClient = new AsyncRestClient(baseUrl);
66         if (logger.isDebugEnabled()) {
67             logger.debug("OscA1Client for ric: {}", ricConfig.name());
68         }
69     }
70
71     public OscA1Client(AsyncRestClient restClient) {
72         this.restClient = restClient;
73     }
74
75     @Override
76     public Mono<List<String>> getPolicyTypeIdentities() {
77         return restClient.get(POLICYTYPES) //
78             .flatMap(this::parseJsonArrayOfString);
79     }
80
81     @Override
82     public Mono<List<String>> getPolicyIdentities() {
83         return getPolicyTypeIdentities() //
84             .flatMapMany(types -> Flux.fromIterable(types)) //
85             .flatMap(type -> getPolicyIdentitiesById(type)) //
86             .flatMap(policyIds -> Flux.fromIterable(policyIds)) //
87             .collectList();
88     }
89
90     @Override
91     public Mono<String> getPolicyTypeSchema(String policyTypeId) {
92         String uri = POLICY_TYPE_SCHEMA_URI.buildAndExpand(policyTypeId).toUriString();
93         return restClient.get(uri) //
94             .flatMap(response -> getCreateSchema(response, policyTypeId));
95     }
96
97     @Override
98     public Mono<String> putPolicy(Policy policy) {
99         String uri = POLICY_URI.buildAndExpand(policy.type().name(), policy.id()).toUriString();
100         return restClient.put(uri, policy.json());
101     }
102
103     @Override
104     public Mono<String> deletePolicy(Policy policy) {
105         return deletePolicyById(policy.type().name(), policy.id());
106     }
107
108     @Override
109     public Mono<A1ProtocolType> getProtocolVersion() {
110         return restClient.get(HEALTHCHECK) //
111             .flatMap(resp -> Mono.just(A1ProtocolType.OSC_V1));
112     }
113
114     @Override
115     public Flux<String> deleteAllPolicies() {
116         return getPolicyTypeIdentities() //
117             .flatMapMany(types -> Flux.fromIterable(types)) //
118             .flatMap(typeId -> deletePoliciesForType(typeId)); //
119     }
120
121     @Override
122     public Mono<String> getPolicyStatus(Policy policy) {
123         String uri = POLICY_STATUS_URI.buildAndExpand(policy.type().name(), policy.id()).toUriString();
124         return restClient.get(uri);
125
126     }
127
128     private Mono<List<String>> getPolicyIdentitiesById(String typeId) {
129         String uri = POLICY_IDS_URI.buildAndExpand(typeId).toUriString();
130         return restClient.get(uri) //
131             .flatMap(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 getPolicyIdentitiesById(typeId) //
153             .flatMapMany(policyIds -> Flux.fromIterable(policyIds)) //
154             .flatMap(policyId -> deletePolicyById(typeId, policyId)); //
155     }
156
157     private Mono<List<String>> parseJsonArrayOfString(String inputString) {
158         try {
159             List<String> arrayList = new ArrayList<>();
160             JSONArray jsonArray = new JSONArray(inputString);
161             for (int i = 0; i < jsonArray.length(); i++) {
162                 arrayList.add(jsonArray.getString(i));
163             }
164             logger.debug("A1 client: received list = {}", arrayList);
165             return Mono.just(arrayList);
166         } catch (JSONException ex) { // invalid json
167             return Mono.error(ex);
168         }
169     }
170 }