5c5a1bb34a215c0ab71f07164f4ceb813ec5aad1
[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(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 || httpCode >= 300 ) {
115             try {
116                 LOG.debug("Config operation Error response code: " + httpCode);
117                 ArrayList<String> errorMessage = new ArrayList<>();
118                 JsonNode responseJson = toJsonNodeFromJsonString(respBody);
119                 if(responseJson!=null && responseJson.get("errors")!=null) {
120                     JsonNode errors = responseJson.get("errors").get("error");
121                     for (Iterator<JsonNode> i = errors.elements();i.hasNext();){
122                         JsonNode error = i.next();
123                         errorMessage.add(error.get("error-message").textValue());
124                     }
125                 }
126                 throw new APPCException("Failed to load config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + errorMessage.toString());
127             } catch (Exception e) {
128                 LOG.error("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(), e);
129                 throw new APPCException("Error while loading config JSON to MD SAL store. Error code:" + httpCode +" Error Message:" + e.getMessage(),e);
130             }
131         }else{
132             LOG.debug("Config operation successful. Response code: " + httpCode);
133         }
134     }
135
136     /**
137      * This is Generic method that can be used to perform REST Put operation
138      * @param url - Destination URL for put
139      * @param body - payload for put action which will be sent as request body.
140      * @return - HttpResponse object which is returned from put REST call.
141      * @throws APPCException
142      */
143     public static HttpResponse doPut (URL url, String body) throws APPCException {
144         HttpPut put;
145         try {
146             put = new HttpPut(url.toExternalForm());
147             put.setHeader(HttpHeaders.CONTENT_TYPE, Constants.OPERATION_APPLICATION_JSON);
148             put.setHeader(HttpHeaders.ACCEPT, Constants.OPERATION_APPLICATION_JSON);
149
150             if (basicAuth != null) {
151                 put.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
152             }
153
154             StringEntity entity = new StringEntity(body);
155             entity.setContentType(Constants.OPERATION_APPLICATION_JSON);
156             put.setEntity(new StringEntity(body));
157         } catch (UnsupportedEncodingException e) {
158             throw new APPCException(e);
159         }
160
161         HttpClient client = getHttpClient();
162
163         try {
164             return client.execute(put);
165         } catch (IOException e) {
166             throw new APPCException(e);
167         }
168
169     }
170
171     /**
172      * Updates the static var URL and returns the value;
173      *
174      * @return The new value of URL
175      */
176     public static String getUrl() {
177         return url.toExternalForm();
178     }
179
180     public static void setUrl(String newUrl) {
181         try {
182             url = new URL(newUrl);
183         } catch (MalformedURLException e) {
184             LOG.error("Malformed URL " +newUrl + e.getMessage(), e);
185         }
186     }
187
188     /**
189      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
190      * to null
191      *
192      * @param user     The user with optional domain name (for AAF)
193      * @param password The password for the user
194      * @return The new value of the basic auth string that will be used in the request headers
195      */
196     public static String setAuthentication(String user, String password) {
197         if (user != null && password != null) {
198             String authStr = user + ":" + password;
199             basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
200         } else {
201             basicAuth = null;
202         }
203         return basicAuth;
204     }
205
206     @SuppressWarnings("deprecation")
207     private static HttpClient getHttpClient() throws APPCException {
208         HttpClient client;
209         if (url.getProtocol().equals(Constants.OPERATION_HTTPS)) {
210             try {
211                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
212                 trustStore.load(null, null);
213                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
214                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
215
216                 HttpParams params = new BasicHttpParams();
217                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
218                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
219
220                 SchemeRegistry registry = new SchemeRegistry();
221                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
222                 registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 443));
223                 registry.register(new Scheme(Constants.OPERATION_HTTPS, sf, 8443));
224                 registry.register(new Scheme("http", sf, 8181));
225
226                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
227                 client = new DefaultHttpClient(ccm, params);
228             } catch (Exception e) {
229                 LOG.error("Error creating HTTP Client. Creating default client." ,  e);
230                 client = new DefaultHttpClient();
231             }
232         } else if ("http".equals(url.getProtocol())) {
233             client = new DefaultHttpClient();
234         } else {
235             throw new APPCException(
236                     "The provider.topology.url property is invalid. The url did not start with http[s]");
237         }
238         return client;
239     }
240
241     @SuppressWarnings("deprecation")
242     private static class MySSLSocketFactory extends SSLSocketFactory {
243         private SSLContext sslContext = SSLContext.getInstance("TLS");
244
245         private MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
246                 KeyStoreException, UnrecoverableKeyException {
247             super(truststore);
248
249             TrustManager tm = new X509TrustManager() {
250                 @Override
251                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
252                     LOG.debug("Inside checkClientTrusted");
253                 }
254
255                 @Override
256                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
257                     LOG.debug("Inside checkServerTrusted");
258                 }
259
260                 @Override
261                 public X509Certificate[] getAcceptedIssuers() {
262                     return new X509Certificate[1];
263                 }
264             };
265
266             sslContext.init(null, new TrustManager[]{
267                     tm
268             }, null);
269         }
270
271         @Override
272         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
273                 throws IOException  {
274             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
275         }
276
277         @Override
278         public Socket createSocket() throws IOException {
279             return sslContext.getSocketFactory().createSocket();
280         }
281     }
282
283     private static JsonNode toJsonNodeFromJsonString(String jsonStr) {
284         JsonNode jsonNode = null;
285         if(jsonStr != null) {
286             try {
287                 jsonNode = mapper.readTree(jsonStr);
288             } catch (IOException e) {
289                 LOG.warn(String.format("Could not map %s to jsonNode.", jsonStr), e);
290             }
291         }
292         return jsonNode;
293     }
294
295 }