Changed to unmaintained
[appc.git] / services / appc-dmaap-service / appc-event-listener-bundle / src / main / java / org / onap / appc / listener / demo / impl / ProviderOperations.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Modifications Copyright (C) 2019 Ericsson
10  * Modifications Copyright (C) 2019 IBM
11  * =============================================================================
12  * Licensed under the Apache License, Version 2.0 (the "License");
13  * you may not use this file except in compliance with the License.
14  * You may obtain a copy of the License at
15  * 
16  *      http://www.apache.org/licenses/LICENSE-2.0
17  * 
18  * Unless required by applicable law or agreed to in writing, software
19  * distributed under the License is distributed on an "AS IS" BASIS,
20  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  * See the License for the specific language governing permissions and
22  * limitations under the License.
23  * 
24  * ============LICENSE_END=========================================================
25  */
26
27 package org.onap.appc.listener.demo.impl;
28
29 import java.io.IOException;
30 import java.io.UnsupportedEncodingException;
31 import java.net.MalformedURLException;
32 import java.net.URL;
33 import org.apache.commons.io.IOUtils;
34 import org.apache.http.HttpResponse;
35 import org.apache.http.client.HttpClient;
36 import org.apache.http.client.methods.HttpPost;
37 import org.apache.http.entity.StringEntity;
38 import org.json.JSONObject;
39 import org.onap.appc.exceptions.APPCException;
40 import org.onap.appc.listener.demo.model.IncomingMessage;
41 import org.onap.appc.listener.util.HttpClientUtil;
42 import org.onap.appc.listener.util.Mapper;
43 import com.att.eelf.configuration.EELFLogger;
44 import com.att.eelf.configuration.EELFManager;
45
46 public class ProviderOperations {
47
48     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
49
50     private static URL url;
51
52     private static String basic_auth;
53
54     //@formatter:off
55     @SuppressWarnings("nls")
56     private final static String TEMPLATE = "{\"input\": {\"common-request-header\": {\"service-request-id\": \"%s\"},\"config-payload\": {\"config-url\": \"%s\",\"config-json\":\"%s\"}}}";
57     //@formatter:on 
58
59     /**
60      * Calls the AppcProvider to run a topology directed graph
61      * 
62      * @param msg
63      *            The incoming message to be run
64      * @return True if the result is success. Never returns false and throws an exception instead.
65      * @throws UnsupportedEncodingException
66      * @throws Exception
67      *             if there was a failure processing the request. The exception message is the failure reason.
68      */
69     @SuppressWarnings("nls")
70     public static boolean topologyDG(IncomingMessage msg) throws APPCException {
71         if (msg == null) {
72             throw new APPCException("Provided message was null");
73         }
74
75         HttpPost post = null;
76         try {
77             // Concatenate the "action" on the end of the URL
78             String path = url.getPath() + ":" + msg.getAction().getValue();
79             URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
80
81             post = new HttpPost(serviceUrl.toExternalForm());
82             post.setHeader("Content-Type", "application/json");
83             post.setHeader("Accept", "application/json");
84
85             // Set Auth
86             if (basic_auth != null) {
87                 post.setHeader("Authorization", "Basic " + basic_auth);
88             }
89
90             //String body = buildReqest(msg.getId(), msg.getUrl(), msg.getIdentityUrl());
91             String body = buildReqest(msg.getHeader().getRequestID(), msg.getPayload().getGenericVnfId(), msg.getPayload().getStreams());
92             StringEntity entity = new StringEntity(body);
93             entity.setContentType("application/json");
94             post.setEntity(new StringEntity(body));
95         } catch (UnsupportedEncodingException | MalformedURLException e) {
96             throw new APPCException(e);
97         }
98
99         HttpClient client = HttpClientUtil.getHttpClient(url.getProtocol());
100
101         int httpCode = 0;
102         String respBody = null;
103         try {
104             HttpResponse response = client.execute(post);
105             httpCode = response.getStatusLine().getStatusCode();
106             respBody = IOUtils.toString(response.getEntity().getContent());
107         } catch (IOException e) {
108             throw new APPCException(e);
109         }
110
111         if (httpCode == 200 && respBody != null) {
112             JSONObject json;
113             try {
114                 json = Mapper.toJsonObject(respBody);
115             } catch (Exception e) {
116                 LOG.error("Error prcoessing response from provider. Could not map response to json", e);
117                 throw new APPCException("APPC has an unknown RPC error");
118             }
119             boolean success;
120             String reason;
121             try {
122                 JSONObject header = json.getJSONObject("output").getJSONObject("common-response-header");
123                 success = header.getBoolean("success");
124                 reason = header.getString("reason");
125             } catch (Exception e) {
126                 LOG.error("Unknown error prcoessing failed response from provider. Json not in expected format", e);
127                 throw new APPCException("APPC has an unknown RPC error");
128             }
129             if (success) {
130                 return true;
131             }
132             String reasonStr = reason == null ? "Unknown" : reason;
133             LOG.warn(String.format("Topology Operation [%s] failed. Reason: %s", msg.getHeader().getRequestID(), reasonStr));
134             throw new APPCException(reasonStr);
135
136         }
137         throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
138     }
139
140     /**
141      * Updates the static var URL and returns the value;
142      * 
143      * @return The new value of URL
144      */
145     public static String getUrl() {
146         return url.toExternalForm();
147     }
148
149     public static void setUrl(String newUrl) {
150         try {
151             url = new URL(newUrl);
152         } catch (MalformedURLException e) {
153             LOG.error("Malformed URL", e);
154         }
155     }
156
157     /**
158      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
159      * to null
160      *
161      * @param user
162      *            The user with optional domain name
163      * @param password
164      *            The password for the user
165      * @return The new value of the basic auth string that will be used in the request headers
166      */
167     public static String setAuthentication(String user, String password) {
168         if (user != null && password != null) {
169             String authStr = user + ":" + password;
170             basic_auth = new String(org.apache.commons.codec.binary.Base64.encodeBase64(authStr.getBytes()));
171         } else {
172             basic_auth = null;
173         }
174         return basic_auth;
175     }
176
177     /**
178      * Builds the request body for a topology operation
179      * 
180      * @param id
181      *            The request id
182      * @param url
183      *            The vm's url
184      *            
185      * @param pgstreams 
186      *           The streams to send to the traffic generator
187      *
188      * @return A String containing the request body
189      */
190     private static String buildReqest(String id, String url, String pgstreams) {
191
192         return String.format(TEMPLATE, id, url, pgstreams);
193     }
194 }