a3d17bc29d7a78a937f94140d1ed7ebb9970a526
[nonrtric.git] / policy-agent / src / main / java / org / oransc / policyagent / clients / A1ClientFactory.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 org.oransc.policyagent.clients.A1Client.A1ProtocolType;
24 import org.oransc.policyagent.exceptions.ServiceException;
25 import org.oransc.policyagent.repository.Ric;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import reactor.core.publisher.Mono;
29
30 public class A1ClientFactory {
31
32     private static final Logger logger = LoggerFactory.getLogger(A1ClientFactory.class);
33
34     public Mono<A1Client> createA1Client(Ric ric) {
35         return getProtocolVersion(ric) //
36             .flatMap(version -> createA1Client(ric, version));
37     }
38
39     private Mono<A1Client> createA1Client(Ric ric, A1ProtocolType version) {
40         if (version == A1ProtocolType.STD_V1) {
41             return Mono.just(createStdA1ClientImpl(ric));
42         }
43         return Mono.error(new ServiceException("Not supported protocoltype: " + version));
44     }
45
46     private Mono<A1Client.A1ProtocolType> getProtocolVersion(Ric ric) {
47         if (ric.getProtocolVersion() == A1ProtocolType.UNKNOWN) {
48             return fetchVersion(ric, new OscA1Client(ric.getConfig())) //
49                 .onErrorResume(err -> fetchVersion(ric, createStdA1ClientImpl(ric)))
50                 .doOnNext(version -> ric.setProtocolVersion(version))
51                 .doOnNext(version -> logger.debug("Recover ric: {}, protocol version:{}", ric.name(), version)) //
52                 .doOnError(t -> logger.warn("Could not get protocol version from RIC: {}", ric.name())); //
53         } else {
54             return Mono.just(ric.getProtocolVersion());
55         }
56     }
57
58     protected A1Client createStdA1ClientImpl(Ric ric) {
59         return new StdA1Client(ric.getConfig());
60     }
61
62     private Mono<A1Client.A1ProtocolType> fetchVersion(Ric ric, A1Client a1Client) {
63         return Mono.just(a1Client) //
64             .flatMap(client -> a1Client.getProtocolVersion());
65     }
66
67 }