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