Actor redesign.
[policy/models.git] / models-interactions / model-actors / actor.sdnc / src / main / java / org / onap / policy / controlloop / actor / sdnc / SdncOperator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
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.onap.policy.controlloop.actor.sdnc;
22
23 import java.util.HashMap;
24 import java.util.Map;
25 import javax.ws.rs.client.Entity;
26 import javax.ws.rs.core.MediaType;
27 import javax.ws.rs.core.Response;
28 import lombok.AccessLevel;
29 import lombok.Getter;
30 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
31 import org.onap.policy.common.endpoints.http.client.HttpClient;
32 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
33 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
34 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
35 import org.onap.policy.common.parameters.ValidationResult;
36 import org.onap.policy.controlloop.ControlLoopOperation;
37 import org.onap.policy.controlloop.VirtualControlLoopEvent;
38 import org.onap.policy.controlloop.actorserviceprovider.Util;
39 import org.onap.policy.controlloop.actorserviceprovider.impl.OperatorPartial;
40 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
41 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams;
42 import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException;
43 import org.onap.policy.controlloop.policy.PolicyResult;
44 import org.onap.policy.sdnc.SdncRequest;
45 import org.onap.policy.sdnc.SdncResponse;
46 import org.onap.policy.sdnc.util.Serialization;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * Superclass for SDNC Operators.
52  */
53 public abstract class SdncOperator extends OperatorPartial {
54     private static final Logger logger = LoggerFactory.getLogger(SdncOperator.class);
55
56     @Getter(AccessLevel.PROTECTED)
57     private HttpClient client;
58
59     /**
60      * URI path for this particular operation.
61      */
62     private String path;
63
64     /**
65      * Constructs the object.
66      *
67      * @param actorName name of the actor with which this operator is associated
68      * @param name operation name
69      */
70     public SdncOperator(String actorName, String name) {
71         super(actorName, name);
72     }
73
74     // TODO add a junit for this and for plug-in via ActorService
75     @Override
76     protected void doConfigure(Map<String, Object> parameters) {
77         HttpParams params = Util.translate(getFullName(), parameters, HttpParams.class);
78         ValidationResult result = params.validate(getFullName());
79         if (!result.isValid()) {
80             throw new ParameterValidationRuntimeException("invalid parameters", result);
81         }
82
83         client = HttpClientFactoryInstance.getClientFactory().get(params.getClientName());
84         path = params.getPath();
85     }
86
87     @Override
88     protected ControlLoopOperation doOperation(ControlLoopOperationParams params, int attempt,
89                     ControlLoopOperation operation) {
90
91         SdncRequest request = constructRequest(params.getContext().getEvent());
92         PolicyResult result = doRequest(request);
93
94         return setOutcome(params, operation, result);
95     }
96
97     /**
98      * Constructs the request.
99      *
100      * @param onset event for which the request should be constructed
101      * @return a new request
102      */
103     protected abstract SdncRequest constructRequest(VirtualControlLoopEvent onset);
104
105     /**
106      * Posts the request and retrieves the response.
107      *
108      * @param sdncRequest request to be posted
109      * @return the result of the request
110      */
111     private PolicyResult doRequest(SdncRequest sdncRequest) {
112         Map<String, Object> headers = new HashMap<>();
113
114         headers.put("Accept", "application/json");
115         String sdncUrl = client.getBaseUrl();
116
117         String sdncRequestJson = Serialization.gsonPretty.toJson(sdncRequest);
118
119         // TODO move this into a utility
120         NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, sdncUrl, sdncRequestJson);
121         logger.info("[OUT|{}|{}|]{}{}", CommInfrastructure.REST, sdncUrl, NetLoggerUtil.SYSTEM_LS, sdncRequestJson);
122
123         Entity<SdncRequest> entity = Entity.entity(sdncRequest, MediaType.APPLICATION_JSON);
124
125         // TODO modify this to use asynchronous client operations
126         Response rawResponse = client.post(path, entity, headers);
127         String strResponse = HttpClient.getBody(rawResponse, String.class);
128
129         // TODO move this into a utility
130         NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, sdncUrl, strResponse);
131         logger.info("[IN|{}|{}|]{}{}", "Sdnc", sdncUrl, NetLoggerUtil.SYSTEM_LS, strResponse);
132         logger.info("Response to Sdnc Heal post:");
133         logger.info(strResponse);
134
135         SdncResponse response = Serialization.gsonPretty.fromJson(strResponse, SdncResponse.class);
136
137         if (response.getResponseOutput() == null || !"200".equals(response.getResponseOutput().getResponseCode())) {
138             logger.info("Sdnc Heal Restcall failed with http error code {}", rawResponse.getStatus());
139             return PolicyResult.FAILURE;
140         }
141
142         return PolicyResult.SUCCESS;
143     }
144 }