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