dbb82468c691dd731ea9a87b5861c211f170d400
[appc.git] / appc-dg / appc-dg-shared / appc-dg-mdsal-store / src / main / java / org / openecomp / appc / mdsal / operation / ConfigOperation.java
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.openecomp.appc.mdsal.operation;
26
27 import org.openecomp.appc.exceptions.APPCException;
28 import org.openecomp.appc.mdsal.impl.Constants;
29 import com.att.eelf.configuration.EELFLogger;
30 import com.att.eelf.configuration.EELFManager;
31 import com.fasterxml.jackson.databind.JsonNode;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import org.apache.commons.codec.binary.Base64;
34 import org.apache.http.HttpHeaders;
35 import org.apache.http.HttpResponse;
36 import org.apache.http.HttpVersion;
37 import org.apache.http.client.HttpClient;
38 import org.apache.http.client.methods.HttpPut;
39 import org.apache.http.conn.ClientConnectionManager;
40 import org.apache.http.conn.scheme.PlainSocketFactory;
41 import org.apache.http.conn.scheme.Scheme;
42 import org.apache.http.conn.scheme.SchemeRegistry;
43 import org.apache.http.conn.ssl.SSLSocketFactory;
44 import org.apache.http.entity.StringEntity;
45 import org.apache.http.impl.client.DefaultHttpClient;
46 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
47 import org.apache.http.params.BasicHttpParams;
48 import org.apache.http.params.HttpParams;
49 import org.apache.http.params.HttpProtocolParams;
50 import org.apache.http.protocol.HTTP;
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.security.*;
61 import java.security.cert.CertificateException;
62 import java.security.cert.X509Certificate;
63 import java.util.ArrayList;
64 import java.util.Iterator;
65
66 import org.apache.commons.io.IOUtils;
67
68 /**
69  * Provides method to store configuration to MD-SAL store. It also exposes doPut operation which can be used to invoke REST Put operation.
70 */
71 public class ConfigOperation {
72     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ConfigOperation.class);
73
74     private static URL url;
75     private static String basicAuth;
76
77     ConfigOperation(){}
78
79     private static ConfigOperationRequestFormatter requestFormatter = new ConfigOperationRequestFormatter();
80
81     private static ObjectMapper mapper = new ObjectMapper();
82
83     /**
84      * This method stores configuration JSON to MD-SAL store. Following input parameters are expected as input
85      * @param configJson - configuration JSON as String. This value will be stored in  MD-SAL store
86      * @param module - Module name that contains yang Schema
87      * @param containerName - yang container name which will be used as base container.
88      * @param subModules - Sub modules list if any. Order of sub module is top to bottom.
89      * @throws APPCException
90      */
91     public static void storeConfig(String configJson , String module, String containerName, String... subModules ) throws APPCException {
92         if (configJson == null) {
93             throw new APPCException("Provided message was null");
94         }
95         LOG.debug("Config JSON: " + configJson +"\n"
96                 +"module" + module +"\n"
97                 +"containerName" + containerName +"\n"
98                 +"subModules length : " + subModules.length );
99
100         int httpCode;
101         String respBody ;
102         try {
103             String path = requestFormatter.buildPath(url, module, containerName, subModules);
104             LOG.debug("Configuration Path : " + path);
105             URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
106             HttpResponse response = doPut(serviceUrl , configJson);
107             httpCode = response.getStatusLine().getStatusCode();
108             respBody = IOUtils.toString(response.getEntity().getContent());
109         } catch (IOException e) {
110             LOG.error("Error while storing configuration json "+e.getMessage(), e);
111             throw new APPCException(e);
112         }
113
114         if (httpCode != 200 ) {
115             try {
116                 ArrayList<String> errorMessage = new ArrayList<>();
117                 JsonNode responseJson = toJsonNodeFromJsonString(respBody);
118                 if(responseJson!=null && responseJson.get("errors")!=null) {
119                     JsonNode errors = responseJson.get("errors").get("error");
120                 for (Iterator<JsonNode> i = errors.elements();i.hasNext();){
121                     JsonNode error = i.next();
122                     errorMessage.add(error.get("error-message").textValue());
123                 }
124                 }
125                 throw new APPCException("Failed to load config JSON to MD SAL store. Error Message:" + errorMessage.toString());
126             } catch (Exception e) {
127                 LOG.error("Error while loading config JSON to MD SAL store. "+e.getMessage(), e);
128                 throw new APPCException("Error while loading config JSON to MD SAL store. "+ e.getMessage(),e);
129             }
130         }
131     }
132
133     /**
134      * This is Generic method that can be used to perform REST Put operation
135      * @param url - Destination URL for put
136      * @param body - payload for put action which will be sent as request body.
137      * @return - HttpResponse object which is returned from put REST call.
138      * @throws APPCException
139      */
140     public static HttpResponse doPut (URL url, String body) throws APPCException {
141         HttpPut put;
142         try {
143             put = new HttpPut(url.toExternalForm());
144             put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON);
145             put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON);
146
147             if (basicAuth != null) {
148                 put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
149             }
150
151             StringEntity entity = new StringEntity(body);
152             entity.setContentType(Constants.OPERATION_APPLICATION_JSON);
153             put.setEntity(new StringEntity(body));
154         } catch (UnsupportedEncodingException e) {
155             throw new APPCException(e);
156         }
157
158         HttpClient client = getHttpClient();
159
160         try {
161             return client.execute(put);
162         } catch (IOException e) {
163             throw new APPCException(e);
164         }
165
166     }
167
168     /**
169      * Updates the static var URL and returns the value;
170      *
171      * @return The new value of URL
172      */
173     public static String getUrl() {
174         return url.toExternalForm();
175     }
176
177     public static void setUrl(String newUrl) {
178         try {
179             url = new URL(newUrl);
180         } catch (MalformedURLException e) {
181             LOG.error("Malformed URL " +newUrl + e.getMessage(), e);
182         }
183     }
184
185     /**
186      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
187      * to null
188      *
189      * @param user     The user with optional domain name (for AAF)
190      * @param password The password for the user
191      * @return The new value of the basic auth string that will be used in the request headers
192      */
193     public static String setAuthentication(String user, String password) {
194         if (user != null && password != null) {
195             String authStr = user + ":" + password;
196             basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
197         } else {
198             basicAuth = null;
199         }
200         return basicAuth;
201     }
202
203     @SuppressWarnings("deprecation")
204     private static HttpClient getHttpClient() throws APPCException {
205         HttpClient client;
206         if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) {
207             try {
208                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
209                 trustStore.load(null, null);
210                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
211                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
212
213                 HttpParams params = new BasicHttpParams();
214                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
215                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
216
217                 SchemeRegistry registry = new SchemeRegistry();
218                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
219                 registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443));
220                 registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443));
221                 registry.register(new Scheme("http", sf, 8181));
222
223                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
224                 client = new DefaultHttpClient(ccm, params);
225             } catch (Exception e) {
226                 LOG.error("Error creating HTTP Client. Creating default client." ,  e);
227                 client = new DefaultHttpClient();
228             }
229         } else if ("http".equals(url.getProtocol())) {
230             client = new DefaultHttpClient();
231         } else {
232             throw new APPCException(
233                     "The provider.topology.url property is invalid. The url did not start with http[s]");
234         }
235         return client;
236     }
237
238     @SuppressWarnings("deprecation")
239     private static class MySSLSocketFactory extends SSLSocketFactory {
240         private SSLContext sslContext = SSLContext.getInstance("TLS");
241
242         private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
243                 KeyStoreException, UnrecoverableKeyException {
244             super(truststore);
245
246             TrustManager tm = new X509TrustManager() {
247                 @Override
248                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
249                     LOG.debug("Inside checkClientTrusted");
250                 }
251
252                 @Override
253                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
254                     LOG.debug("Inside checkServerTrusted");
255                 }
256
257                 @Override
258                 public X509Certificate[] getAcceptedIssuers() {
259                     return new X509Certificate[1];
260                 }
261             };
262
263             sslContext.init(null, new TrustManager[]{
264                     tm
265             }, null);
266         }
267
268         @Override
269         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
270                 throws IOException  {
271             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
272         }
273
274         @Override
275         public Socket createSocket() throws IOException {
276             return sslContext.getSocketFactory().createSocket();
277         }
278     }
279
280     private static JsonNode toJsonNodeFromJsonString(String jsonStr) {
281         JsonNode jsonNode = null;
282         if(jsonStr != null) {
283             try {
284                 jsonNode = mapper.readTree(jsonStr);
285             } catch (IOException e) {
286                 LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e);
287             }
288         }
289         return jsonNode;
290     }
291
292 }