6cd2f2d766b57c49621161818871150b2ec00a9d
[appc.git] / appc-event-listener / 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.codec.binary.Base64;
34 import org.apache.commons.io.IOUtils;
35 import org.apache.http.HttpResponse;
36 import org.apache.http.client.HttpClient;
37 import org.apache.http.client.methods.HttpPost;
38 import org.apache.http.entity.StringEntity;
39 import org.json.JSONObject;
40 import org.onap.appc.exceptions.APPCException;
41 import org.onap.appc.listener.demo.model.IncomingMessage;
42 import org.onap.appc.listener.util.HttpClientUtil;
43 import org.onap.appc.listener.util.Mapper;
44 import com.att.eelf.configuration.EELFLogger;
45 import com.att.eelf.configuration.EELFManager;
46
47 public class ProviderOperations {
48
49     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
50
51     private static URL url;
52
53     private static String basic_auth;
54
55     //@formatter:off
56     @SuppressWarnings("nls")
57     private final static String TEMPLATE = "{\"input\": {\"common-request-header\": {\"service-request-id\": \"%s\"},\"config-payload\": {\"config-url\": \"%s\",\"config-json\":\"%s\"}}}";
58     //@formatter:on 
59
60     /**
61      * Calls the AppcProvider to run a topology directed graph
62      * 
63      * @param msg
64      *            The incoming message to be run
65      * @return True if the result is success. Never returns false and throws an exception instead.
66      * @throws UnsupportedEncodingException
67      * @throws Exception
68      *             if there was a failure processing the request. The exception message is the failure reason.
69      */
70     @SuppressWarnings("nls")
71     public static boolean topologyDG(IncomingMessage msg) throws APPCException {
72         if (msg == null) {
73             throw new APPCException("Provided message was null");
74         }
75
76         HttpPost post = null;
77         try {
78             // Concatenate the "action" on the end of the URL
79             String path = url.getPath() + ":" + msg.getAction().getValue();
80             URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
81
82             post = new HttpPost(serviceUrl.toExternalForm());
83             post.setHeader("Content-Type", "application/json");
84             post.setHeader("Accept", "application/json");
85
86             // Set Auth
87             if (basic_auth != null) {
88                 post.setHeader("Authorization", "Basic " + basic_auth);
89             }
90
91             //String body = buildReqest(msg.getId(), msg.getUrl(), msg.getIdentityUrl());
92             String body = buildReqest(msg.getHeader().getRequestID(), msg.getPayload().getGenericVnfId(), msg.getPayload().getStreams());
93             StringEntity entity = new StringEntity(body);
94             entity.setContentType("application/json");
95             post.setEntity(new StringEntity(body));
96         } catch (UnsupportedEncodingException | MalformedURLException e) {
97             throw new APPCException(e);
98         }
99
100         HttpClient client = HttpClientUtil.getHttpClient(url.getProtocol());
101
102         int httpCode = 0;
103         String respBody = null;
104         try {
105             HttpResponse response = client.execute(post);
106             httpCode = response.getStatusLine().getStatusCode();
107             respBody = IOUtils.toString(response.getEntity().getContent());
108         } catch (IOException e) {
109             throw new APPCException(e);
110         }
111
112         if (httpCode == 200 && respBody != null) {
113             JSONObject json;
114             try {
115                 json = Mapper.toJsonObject(respBody);
116             } catch (Exception e) {
117                 LOG.error("Error prcoessing response from provider. Could not map response to json", e);
118                 throw new APPCException("APPC has an unknown RPC error");
119             }
120             boolean success;
121             String reason;
122             try {
123                 JSONObject header = json.getJSONObject("output").getJSONObject("common-response-header");
124                 success = header.getBoolean("success");
125                 reason = header.getString("reason");
126             } catch (Exception e) {
127                 LOG.error("Unknown error prcoessing failed response from provider. Json not in expected format", e);
128                 throw new APPCException("APPC has an unknown RPC error");
129             }
130             if (success) {
131                 return true;
132             }
133             String reasonStr = reason == null ? "Unknown" : reason;
134             LOG.warn(String.format("Topology Operation [%s] failed. Reason: %s", msg.getHeader().getRequestID(), reasonStr));
135             throw new APPCException(reasonStr);
136
137         }
138         throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
139     }
140
141     /**
142      * Updates the static var URL and returns the value;
143      * 
144      * @return The new value of URL
145      */
146     public static String getUrl() {
147         return url.toExternalForm();
148     }
149
150     public static void setUrl(String newUrl) {
151         try {
152             url = new URL(newUrl);
153         } catch (MalformedURLException e) {
154             LOG.error("Malformed URL", e);
155         }
156     }
157
158     /**
159      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
160      * to null
161      *
162      * @param user
163      *            The user with optional domain name
164      * @param password
165      *            The password for the user
166      * @return The new value of the basic auth string that will be used in the request headers
167      */
168     public static String setAuthentication(String user, String password) {
169         if (user != null && password != null) {
170             String authStr = user + ":" + password;
171             basic_auth = new String(org.apache.commons.codec.binary.Base64.encodeBase64(authStr.getBytes()));
172         } else {
173             basic_auth = null;
174         }
175         return basic_auth;
176     }
177
178     /**
179      * Builds the request body for a topology operation
180      * 
181      * @param id
182      *            The request id
183      * @param url
184      *            The vm's url
185      *            
186      * @param pgstreams 
187      *           The streams to send to the traffic generator
188      *
189      * @return A String containing the request body
190      */
191     private static String buildReqest(String id, String url, String pgstreams) {
192
193         return String.format(TEMPLATE, id, url, pgstreams);
194     }
195 }