c077076af7283d45c918dbbd8efd65c69ac72685
[appc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22
23 package org.openecomp.appc.listener.LCM.operation;
24
25 import com.fasterxml.jackson.databind.JsonNode;
26 import org.apache.commons.codec.binary.Base64;
27 import org.apache.commons.io.IOUtils;
28 import org.apache.http.HttpHeaders;
29 import org.apache.http.HttpResponse;
30 import org.apache.http.HttpVersion;
31 import org.apache.http.client.HttpClient;
32 import org.apache.http.client.methods.HttpPost;
33 import org.apache.http.conn.ClientConnectionManager;
34 import org.apache.http.conn.scheme.PlainSocketFactory;
35 import org.apache.http.conn.scheme.Scheme;
36 import org.apache.http.conn.scheme.SchemeRegistry;
37 import org.apache.http.conn.ssl.SSLSocketFactory;
38 import org.apache.http.entity.StringEntity;
39 import org.apache.http.impl.client.DefaultHttpClient;
40 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
41 import org.apache.http.params.BasicHttpParams;
42 import org.apache.http.params.HttpParams;
43 import org.apache.http.params.HttpProtocolParams;
44 import org.apache.http.protocol.HTTP;
45 import org.openecomp.appc.exceptions.APPCException;
46 import org.openecomp.appc.listener.LCM.model.ResponseStatus;
47 import org.openecomp.appc.listener.util.Mapper;
48
49 import com.att.eelf.configuration.EELFLogger;
50 import com.att.eelf.configuration.EELFManager;
51
52 import javax.net.ssl.SSLContext;
53 import javax.net.ssl.TrustManager;
54 import javax.net.ssl.X509TrustManager;
55 import java.io.IOException;
56 import java.io.UnsupportedEncodingException;
57 import java.net.MalformedURLException;
58 import java.net.Socket;
59 import java.net.URL;
60 import java.net.UnknownHostException;
61 import java.security.*;
62 import java.security.cert.CertificateException;
63 import java.security.cert.X509Certificate;
64
65 public class ProviderOperations {
66
67     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
68
69     private URL url;
70     private String basic_auth;
71
72     private static ProviderOperationRequestFormatter requestFormatter = new GenericProviderOperationRequestFormatter();
73
74     /**
75      * Calls the AppcProvider to run a topology directed graph
76      *
77      * @param msg The incoming message to be run
78      * @return True if the result is success. Never returns false and throws an exception instead.
79      * @throws UnsupportedEncodingException
80      * @throws Exception                    if there was a failure processing the request. The exception message is the failure reason.
81      */
82     @SuppressWarnings("nls")
83     public JsonNode topologyDG(String rpcName, JsonNode msg) throws APPCException {
84         if (msg == null) {
85             throw new APPCException("Provided message was null");
86         }
87
88         HttpPost post = null;
89         try {
90
91             // Concatenate the "action" on the end of the URL
92             String path = requestFormatter.buildPath(url, rpcName);
93             URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
94
95             post = new HttpPost(serviceUrl.toExternalForm());
96             post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
97             post.setHeader(HttpHeaders.ACCEPT, "application/json");
98
99             // Set Auth
100             if (basic_auth != null) {
101                 post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basic_auth);
102             }
103
104             String body = Mapper.toJsonString(msg);
105             StringEntity entity = new StringEntity(body);
106             entity.setContentType("application/json");
107             post.setEntity(new StringEntity(body));
108         } catch (UnsupportedEncodingException | MalformedURLException e) {
109             throw new APPCException(e);
110         }
111
112         HttpClient client = getHttpClient();
113
114         int httpCode = 0;
115         String respBody = null;
116         try {
117             HttpResponse response = client.execute(post);
118             httpCode = response.getStatusLine().getStatusCode();
119             respBody = IOUtils.toString(response.getEntity().getContent());
120         } catch (IOException e) {
121             throw new APPCException(e);
122         }
123
124         if (httpCode >= 200 && httpCode < 300 && respBody != null) {
125             JsonNode json;
126             try {
127                 json = Mapper.toJsonNodeFromJsonString(respBody);
128             } catch (Exception e) {
129                 LOG.error("Error processing response from provider. Could not map response to json", e);
130                 throw new APPCException("APPC has an unknown RPC error");
131             }
132
133             ResponseStatus responseStatus = requestFormatter.getResponseStatus(json);
134
135             if (!isSucceeded(responseStatus.getCode())) {
136                 LOG.warn(String.format("Operation failed [%s]", msg.toString()));
137             }
138
139             return json;
140         }
141
142         throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
143     }
144
145     /**
146      * Updates the static var URL and returns the value;
147      *
148      * @return The new value of URL
149      */
150     public String getUrl() {
151         return url.toExternalForm();
152     }
153
154     public void setUrl(String newUrl) {
155         try {
156             url = new URL(newUrl);
157         } catch (MalformedURLException e) {
158             e.printStackTrace();
159         }
160     }
161
162     /**
163      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
164      * to null
165      *
166      * @param user     The user with optional domain name
167      * @param password The password for the user
168      * @return The new value of the basic auth string that will be used in the request headers
169      */
170     public String setAuthentication(String user, String password) {
171         if (user != null && password != null) {
172             String authStr = user + ":" + password;
173             basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
174         } else {
175             basic_auth = null;
176         }
177         return basic_auth;
178     }
179
180     @SuppressWarnings("deprecation")
181     private HttpClient getHttpClient() throws APPCException {
182         HttpClient client;
183         if (url.getProtocol().equals("https")) {
184             try {
185                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
186                 trustStore.load(null, null);
187                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
188                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
189
190                 HttpParams params = new BasicHttpParams();
191                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
192                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
193
194                 SchemeRegistry registry = new SchemeRegistry();
195                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
196                 registry.register(new Scheme("https", sf, 443));
197                 registry.register(new Scheme("https", sf, 8443));
198                 registry.register(new Scheme("http", sf, 8181));
199
200                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
201                 client = new DefaultHttpClient(ccm, params);
202             } catch (Exception e) {
203                 client = new DefaultHttpClient();
204             }
205         } else if (url.getProtocol().equals("http")) {
206             client = new DefaultHttpClient();
207         } else {
208             throw new APPCException(
209                     "The provider.topology.url property is invalid. The url did not start with http[s]");
210         }
211         return client;
212     }
213
214     @SuppressWarnings("deprecation")
215     public static class MySSLSocketFactory extends SSLSocketFactory {
216         private SSLContext sslContext = SSLContext.getInstance("TLS");
217
218         public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
219                 KeyStoreException, UnrecoverableKeyException {
220             super(truststore);
221
222             TrustManager tm = new X509TrustManager() {
223                 @Override
224                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
225                 }
226
227                 @Override
228                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
229                 }
230
231                 @Override
232                 public X509Certificate[] getAcceptedIssuers() {
233                     return null;
234                 }
235             };
236
237             sslContext.init(null, new TrustManager[]{
238                     tm
239             }, null);
240         }
241
242         @Override
243         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
244                 throws IOException, UnknownHostException {
245             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
246         }
247
248         @Override
249         public Socket createSocket() throws IOException {
250             return sslContext.getSocketFactory().createSocket();
251         }
252     }
253
254     public static boolean isSucceeded(Integer code) {
255         if (code == null) {
256             return false;
257         }
258         return ((code == 100) || (code == 400)); // only 100 & 400 statuses are success
259     }
260
261 }